Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add two functions to check type of given address #36707

Merged
merged 1 commit into from
Oct 11, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/libstd/net/ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,24 @@ impl IpAddr {
IpAddr::V6(ref a) => a.is_documentation(),
}
}

/// Returns true if this address is a valid IPv4 address, false if it's a valid IPv6 address.
#[unstable(feature = "ipaddr_checker", issue = "36949")]
pub fn is_ipv4(&self) -> bool {
match *self {
IpAddr::V4(_) => true,
IpAddr::V6(_) => false,
}
}

/// Returns true if this address is a valid IPv6 address, false if it's a valid IPv4 address.
#[unstable(feature = "ipaddr_checker", issue = "36949")]
pub fn is_ipv6(&self) -> bool {
match *self {
IpAddr::V4(_) => false,
IpAddr::V6(_) => true,
}
}
}

impl Ipv4Addr {
Expand Down Expand Up @@ -1023,4 +1041,18 @@ mod tests {
assert!("2001:db8:f00::1002".parse::<Ipv6Addr>().unwrap() <
"2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap());
}

#[test]
fn is_v4() {
let ip = IpAddr::V4(Ipv4Addr::new(100, 64, 3, 3));
assert!(ip.is_ipv4());
assert!(!ip.is_ipv6());
}

#[test]
fn is_v6() {
let ip = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678));
assert!(!ip.is_ipv4());
assert!(ip.is_ipv6());
}
}