Skip to content

Commit ead9212

Browse files
authored
Auto merge of #36707 - achanda:ip_type, r=alexcrichton
Add two functions to check type of given address The is_v4 function returns true if the given IP is v4. The is_v6 function returns true if the IP is v6.
2 parents a3bc191 + 80a7a3c commit ead9212

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/libstd/net/ip.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,24 @@ impl IpAddr {
130130
IpAddr::V6(ref a) => a.is_documentation(),
131131
}
132132
}
133+
134+
/// Returns true if this address is a valid IPv4 address, false if it's a valid IPv6 address.
135+
#[unstable(feature = "ipaddr_checker", issue = "36949")]
136+
pub fn is_ipv4(&self) -> bool {
137+
match *self {
138+
IpAddr::V4(_) => true,
139+
IpAddr::V6(_) => false,
140+
}
141+
}
142+
143+
/// Returns true if this address is a valid IPv6 address, false if it's a valid IPv4 address.
144+
#[unstable(feature = "ipaddr_checker", issue = "36949")]
145+
pub fn is_ipv6(&self) -> bool {
146+
match *self {
147+
IpAddr::V4(_) => false,
148+
IpAddr::V6(_) => true,
149+
}
150+
}
133151
}
134152

135153
impl Ipv4Addr {
@@ -1022,4 +1040,18 @@ mod tests {
10221040
assert!("2001:db8:f00::1002".parse::<Ipv6Addr>().unwrap() <
10231041
"2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap());
10241042
}
1043+
1044+
#[test]
1045+
fn is_v4() {
1046+
let ip = IpAddr::V4(Ipv4Addr::new(100, 64, 3, 3));
1047+
assert!(ip.is_ipv4());
1048+
assert!(!ip.is_ipv6());
1049+
}
1050+
1051+
#[test]
1052+
fn is_v6() {
1053+
let ip = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678));
1054+
assert!(!ip.is_ipv4());
1055+
assert!(ip.is_ipv6());
1056+
}
10251057
}

0 commit comments

Comments
 (0)