Skip to content

Commit 9cb0136

Browse files
authored
Auto merge of #36762 - achanda:sockaddr_type, r=alexcrichton
Add two functions to check type of SockAddr These can be used to determine the type of the underlying IP address r? @alexcrichton
2 parents acb50e3 + d9e6430 commit 9cb0136

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/libstd/net/addr.rs

+35
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,26 @@ impl SocketAddr {
9393
SocketAddr::V6(ref mut a) => a.set_port(new_port),
9494
}
9595
}
96+
97+
/// Returns true if the IP in this `SocketAddr` is a valid IPv4 address,
98+
/// false if it's a valid IPv6 address.
99+
#[unstable(feature = "sockaddr_checker", issue = "36949")]
100+
pub fn is_ipv4(&self) -> bool {
101+
match *self {
102+
SocketAddr::V4(_) => true,
103+
SocketAddr::V6(_) => false,
104+
}
105+
}
106+
107+
/// Returns true if the IP in this `SocketAddr` is a valid IPv6 address,
108+
/// false if it's a valid IPv4 address.
109+
#[unstable(feature = "sockaddr_checker", issue = "36949")]
110+
pub fn is_ipv6(&self) -> bool {
111+
match *self {
112+
SocketAddr::V4(_) => false,
113+
SocketAddr::V6(_) => true,
114+
}
115+
}
96116
}
97117

98118
impl SocketAddrV4 {
@@ -631,4 +651,19 @@ mod tests {
631651
v6.set_scope_id(20);
632652
assert_eq!(v6.scope_id(), 20);
633653
}
654+
655+
#[test]
656+
fn is_v4() {
657+
let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
658+
assert!(v4.is_ipv4());
659+
assert!(!v4.is_ipv6());
660+
}
661+
662+
#[test]
663+
fn is_v6() {
664+
let v6 = SocketAddr::V6(SocketAddrV6::new(
665+
Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
666+
assert!(!v6.is_ipv4());
667+
assert!(v6.is_ipv6());
668+
}
634669
}

0 commit comments

Comments
 (0)