about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2016-10-12 11:28:53 -0700
committerGitHub <noreply@github.com>2016-10-12 11:28:53 -0700
commit9cb01365eed598811aef847a8ee414dab576f3c8 (patch)
treef5888ef42613e9df1315df2847a575775b2a00fa /src/libstd
parentacb50e3481a06089dbd13d860dadc7d8d7cd1649 (diff)
parentd9e64301856354cc22aaf5b92bfc6ac8b1beb50e (diff)
downloadrust-9cb01365eed598811aef847a8ee414dab576f3c8.tar.gz
rust-9cb01365eed598811aef847a8ee414dab576f3c8.zip
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
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/net/addr.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs
index 58daa7dbf8d..20dc5b3801b 100644
--- a/src/libstd/net/addr.rs
+++ b/src/libstd/net/addr.rs
@@ -93,6 +93,26 @@ impl SocketAddr {
             SocketAddr::V6(ref mut a) => a.set_port(new_port),
         }
     }
+
+    /// Returns true if the IP in this `SocketAddr` is a valid IPv4 address,
+    /// false if it's a valid IPv6 address.
+    #[unstable(feature = "sockaddr_checker", issue = "36949")]
+    pub fn is_ipv4(&self) -> bool {
+        match *self {
+            SocketAddr::V4(_) => true,
+            SocketAddr::V6(_) => false,
+        }
+    }
+
+    /// Returns true if the IP in this `SocketAddr` is a valid IPv6 address,
+    /// false if it's a valid IPv4 address.
+    #[unstable(feature = "sockaddr_checker", issue = "36949")]
+    pub fn is_ipv6(&self) -> bool {
+        match *self {
+            SocketAddr::V4(_) => false,
+            SocketAddr::V6(_) => true,
+        }
+    }
 }
 
 impl SocketAddrV4 {
@@ -631,4 +651,19 @@ mod tests {
         v6.set_scope_id(20);
         assert_eq!(v6.scope_id(), 20);
     }
+
+    #[test]
+    fn is_v4() {
+        let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
+        assert!(v4.is_ipv4());
+        assert!(!v4.is_ipv6());
+    }
+
+    #[test]
+    fn is_v6() {
+        let v6 = SocketAddr::V6(SocketAddrV6::new(
+                Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
+        assert!(!v6.is_ipv4());
+        assert!(v6.is_ipv6());
+    }
 }