@@ -171,7 +171,6 @@ impl Ipv4Addr {
171171 ( ( self . octets ( ) [ 0 ] as u16 ) << 8 ) | self . octets ( ) [ 1 ] as u16 ,
172172 ( ( self . octets ( ) [ 2 ] as u16 ) << 8 ) | self . octets ( ) [ 3 ] as u16 )
173173 }
174-
175174}
176175
177176#[ stable( feature = "rust1" , since = "1.0.0" ) ]
@@ -244,6 +243,21 @@ impl FromInner<libc::in_addr> for Ipv4Addr {
244243 }
245244}
246245
246+ #[ stable( feature = "ip_u32" , since = "1.1.0" ) ]
247+ impl From < Ipv4Addr > for u32 {
248+ fn from ( ip : Ipv4Addr ) -> u32 {
249+ let ip = ip. octets ( ) ;
250+ ( ( ip[ 0 ] as u32 ) << 24 ) + ( ( ip[ 1 ] as u32 ) << 16 ) + ( ( ip[ 2 ] as u32 ) << 8 ) + ( ip[ 3 ] as u32 )
251+ }
252+ }
253+
254+ #[ stable( feature = "ip_u32" , since = "1.1.0" ) ]
255+ impl From < u32 > for Ipv4Addr {
256+ fn from ( ip : u32 ) -> Ipv4Addr {
257+ Ipv4Addr :: new ( ( ip >> 24 ) as u8 , ( ip >> 16 ) as u8 , ( ip >> 8 ) as u8 , ip as u8 )
258+ }
259+ }
260+
247261impl Ipv6Addr {
248262 /// Creates a new IPv6 address from eight 16-bit segments.
249263 ///
@@ -738,4 +752,16 @@ mod tests {
738752 let a = sa4 ( Ipv4Addr :: new ( 77 , 88 , 21 , 11 ) , 12345 ) ;
739753 assert_eq ! ( Ok ( vec![ a] ) , tsa( a) ) ;
740754 }
755+
756+ #[ test]
757+ fn test_ipv4_to_int ( ) {
758+ let a = Ipv4Addr :: new ( 127 , 0 , 0 , 1 ) ;
759+ assert_eq ! ( u32 :: from( a) , 2130706433 ) ;
760+ }
761+
762+ #[ test]
763+ fn test_int_to_ipv4 ( ) {
764+ let a = Ipv4Addr :: new ( 127 , 0 , 0 , 1 ) ;
765+ assert_eq ! ( Ipv4Addr :: from( 2130706433 ) , a) ;
766+ }
741767}
0 commit comments