about summary refs log tree commit diff
path: root/src/libstd/net/ip.rs
diff options
context:
space:
mode:
authorAbhishek Chanda <abhishek@cloudscaling.com>2015-04-20 20:37:58 -0700
committerAbhishek Chanda <abhishek@cloudscaling.com>2015-05-03 19:08:53 -0700
commit285ab0266c7dd540d2d8df202cd1773fcd2fc572 (patch)
treec9882deae4c7cf7ab076888a6cbf2cd25e5565a2 /src/libstd/net/ip.rs
parente959fab4a520ed9c08f8eec0340457fa4b1597f2 (diff)
downloadrust-285ab0266c7dd540d2d8df202cd1773fcd2fc572.tar.gz
rust-285ab0266c7dd540d2d8df202cd1773fcd2fc572.zip
Add functions to convert IPv4 to long and back
Diffstat (limited to 'src/libstd/net/ip.rs')
-rw-r--r--src/libstd/net/ip.rs28
1 files changed, 27 insertions, 1 deletions
diff --git a/src/libstd/net/ip.rs b/src/libstd/net/ip.rs
index 065126c6fdb..b40d5628041 100644
--- a/src/libstd/net/ip.rs
+++ b/src/libstd/net/ip.rs
@@ -171,7 +171,6 @@ impl Ipv4Addr {
                       ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
                       ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
     }
-
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -244,6 +243,21 @@ impl FromInner<libc::in_addr> for Ipv4Addr {
     }
 }
 
+#[stable(feature = "ip_u32", since = "1.1.0")]
+impl From<Ipv4Addr> for u32 {
+    fn from(ip: Ipv4Addr) -> u32 {
+        let ip = ip.octets();
+        ((ip[0] as u32) << 24) + ((ip[1] as u32) << 16) + ((ip[2] as u32) << 8) + (ip[3] as u32)
+    }
+}
+
+#[stable(feature = "ip_u32", since = "1.1.0")]
+impl From<u32> for Ipv4Addr {
+    fn from(ip: u32) -> Ipv4Addr {
+        Ipv4Addr::new((ip >> 24) as u8, (ip >> 16) as u8, (ip >> 8) as u8, ip as u8)
+    }
+}
+
 impl Ipv6Addr {
     /// Creates a new IPv6 address from eight 16-bit segments.
     ///
@@ -738,4 +752,16 @@ mod tests {
         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 12345);
         assert_eq!(Ok(vec![a]), tsa(a));
     }
+
+    #[test]
+    fn test_ipv4_to_int() {
+        let a = Ipv4Addr::new(127, 0, 0, 1);
+        assert_eq!(u32::from(a), 2130706433);
+    }
+
+    #[test]
+    fn test_int_to_ipv4() {
+        let a = Ipv4Addr::new(127, 0, 0, 1);
+        assert_eq!(Ipv4Addr::from(2130706433), a);
+    }
 }