Skip to content

Commit 80a7a3c

Browse files
committed
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.
1 parent bdad702 commit 80a7a3c

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 {
@@ -1023,4 +1041,18 @@ mod tests {
10231041
assert!("2001:db8:f00::1002".parse::<Ipv6Addr>().unwrap() <
10241042
"2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap());
10251043
}
1044+
1045+
#[test]
1046+
fn is_v4() {
1047+
let ip = IpAddr::V4(Ipv4Addr::new(100, 64, 3, 3));
1048+
assert!(ip.is_ipv4());
1049+
assert!(!ip.is_ipv6());
1050+
}
1051+
1052+
#[test]
1053+
fn is_v6() {
1054+
let ip = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678));
1055+
assert!(!ip.is_ipv4());
1056+
assert!(ip.is_ipv6());
1057+
}
10261058
}

0 commit comments

Comments
 (0)