@@ -174,7 +174,6 @@ impl Ipv4Addr {
174174 ( ( self . octets ( ) [ 0 ] as u16 ) << 8 ) | self . octets ( ) [ 1 ] as u16 ,
175175 ( ( self . octets ( ) [ 2 ] as u16 ) << 8 ) | self . octets ( ) [ 3 ] as u16 )
176176 }
177-
178177}
179178
180179#[ stable( feature = "rust1" , since = "1.0.0" ) ]
@@ -247,6 +246,21 @@ impl FromInner<libc::in_addr> for Ipv4Addr {
247246 }
248247}
249248
249+ #[ stable( feature = "ip_u32" , since = "1.1.0" ) ]
250+ impl From < Ipv4Addr > for u32 {
251+ fn from ( ip : Ipv4Addr ) -> u32 {
252+ let ip = ip. octets ( ) ;
253+ ( ( ip[ 0 ] as u32 ) << 24 ) + ( ( ip[ 1 ] as u32 ) << 16 ) + ( ( ip[ 2 ] as u32 ) << 8 ) + ( ip[ 3 ] as u32 )
254+ }
255+ }
256+
257+ #[ stable( feature = "ip_u32" , since = "1.1.0" ) ]
258+ impl From < u32 > for Ipv4Addr {
259+ fn from ( ip : u32 ) -> Ipv4Addr {
260+ Ipv4Addr :: new ( ( ip >> 24 ) as u8 , ( ip >> 16 ) as u8 , ( ip >> 8 ) as u8 , ip as u8 )
261+ }
262+ }
263+
250264impl Ipv6Addr {
251265 /// Creates a new IPv6 address from eight 16-bit segments.
252266 ///
@@ -746,4 +760,16 @@ mod tests {
746760 let a = sa4 ( Ipv4Addr :: new ( 77 , 88 , 21 , 11 ) , 12345 ) ;
747761 assert_eq ! ( Ok ( vec![ a] ) , tsa( a) ) ;
748762 }
763+
764+ #[ test]
765+ fn test_ipv4_to_int ( ) {
766+ let a = Ipv4Addr :: new ( 127 , 0 , 0 , 1 ) ;
767+ assert_eq ! ( u32 :: from( a) , 2130706433 ) ;
768+ }
769+
770+ #[ test]
771+ fn test_int_to_ipv4 ( ) {
772+ let a = Ipv4Addr :: new ( 127 , 0 , 0 , 1 ) ;
773+ assert_eq ! ( Ipv4Addr :: from( 2130706433 ) , a) ;
774+ }
749775}
0 commit comments