]> git.lizzy.rs Git - rust.git/commitdiff
Add two functions to check type of SockAddr
authorAbhishek Chanda <abhishek.becs@gmail.com>
Tue, 27 Sep 2016 00:16:34 +0000 (17:16 -0700)
committerAbhishek Chanda <abhishek.becs@gmail.com>
Tue, 4 Oct 2016 04:12:37 +0000 (21:12 -0700)
These can be used to determine the type of the underlying IP
address

src/libstd/net/addr.rs

index d0b59b42c1798a73a2ca56e75d553849ea5a9672..3fa917cbf9e19bd4c6ac516cb863a27e5dabf692 100644 (file)
@@ -93,6 +93,26 @@ pub fn set_port(&mut self, new_port: u16) {
             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 @@ fn set_scope_id() {
         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());
+    }
 }