@@ -36,6 +36,7 @@ use std::hash::{Hash, Hasher};
36
36
use std:: os:: unix:: ffi:: OsStrExt ;
37
37
use std:: path:: Path ;
38
38
use std:: { fmt, mem, net, ptr, slice} ;
39
+ use std:: net:: { Ipv4Addr , Ipv6Addr } ;
39
40
40
41
/// Convert a std::net::Ipv4Addr into the libc form.
41
42
#[ cfg( feature = "net" ) ]
@@ -1006,8 +1007,10 @@ pub struct SockaddrIn(libc::sockaddr_in);
1006
1007
impl SockaddrIn {
1007
1008
/// Returns the IP address associated with this socket address, in native
1008
1009
/// endian.
1009
- pub const fn ip ( & self ) -> libc:: in_addr_t {
1010
- u32:: from_be ( self . 0 . sin_addr . s_addr )
1010
+ pub const fn ip ( & self ) -> net:: Ipv4Addr {
1011
+ let bytes = self . 0 . sin_addr . s_addr . to_ne_bytes ( ) ;
1012
+ let ( a, b, c, d) = ( bytes[ 0 ] , bytes[ 1 ] , bytes[ 2 ] , bytes[ 3 ] ) ;
1013
+ Ipv4Addr :: new ( a, b, c, d)
1011
1014
}
1012
1015
1013
1016
/// Creates a new socket address from IPv4 octets and a port number.
@@ -1143,8 +1146,18 @@ impl SockaddrIn6 {
1143
1146
}
1144
1147
1145
1148
/// Returns the IP address associated with this socket address.
1146
- pub fn ip ( & self ) -> net:: Ipv6Addr {
1147
- net:: Ipv6Addr :: from ( self . 0 . sin6_addr . s6_addr )
1149
+ pub const fn ip ( & self ) -> net:: Ipv6Addr {
1150
+ let bytes = self . 0 . sin6_addr . s6_addr ;
1151
+ let ( a, b, c, d, e, f, g, h) = ( ( ( bytes[ 0 ] as u16 ) << 8 ) | bytes[ 1 ] as u16 ,
1152
+ ( ( bytes[ 2 ] as u16 ) << 8 ) | bytes[ 3 ] as u16 ,
1153
+ ( ( bytes[ 4 ] as u16 ) << 8 ) | bytes[ 5 ] as u16 ,
1154
+ ( ( bytes[ 6 ] as u16 ) << 8 ) | bytes[ 7 ] as u16 ,
1155
+ ( ( bytes[ 8 ] as u16 ) << 8 ) | bytes[ 9 ] as u16 ,
1156
+ ( ( bytes[ 10 ] as u16 ) << 8 ) | bytes[ 11 ] as u16 ,
1157
+ ( ( bytes[ 12 ] as u16 ) << 8 ) | bytes[ 13 ] as u16 ,
1158
+ ( ( bytes[ 14 ] as u16 ) << 8 ) | bytes[ 15 ] as u16
1159
+ ) ;
1160
+ Ipv6Addr :: new ( a, b, c, d, e, f, g, h)
1148
1161
}
1149
1162
1150
1163
/// Returns the port number associated with this socket address, in native
@@ -2588,6 +2601,13 @@ mod tests {
2588
2601
SockaddrIn :: size( ) as usize
2589
2602
) ;
2590
2603
}
2604
+
2605
+ #[ test]
2606
+ fn ip ( ) {
2607
+ let s = "127.0.0.1:8080" ;
2608
+ let ip = SockaddrIn :: from_str ( s) . unwrap ( ) . ip ( ) ;
2609
+ assert_eq ! ( "127.0.0.1" , format!( "{ip}" ) ) ;
2610
+ }
2591
2611
}
2592
2612
2593
2613
mod sockaddr_in6 {
@@ -2609,6 +2629,14 @@ mod tests {
2609
2629
) ;
2610
2630
}
2611
2631
2632
+ #[ test]
2633
+ fn ip ( ) {
2634
+ let s = "[1234:5678:90ab:cdef::1111:2222]:8080" ;
2635
+ let ip = SockaddrIn6 :: from_str ( s) . unwrap ( ) . ip ( ) ;
2636
+ assert_eq ! ( "1234:5678:90ab:cdef::1111:2222" , format!( "{ip}" ) ) ;
2637
+
2638
+ }
2639
+
2612
2640
#[ test]
2613
2641
// Ensure that we can convert to-and-from std::net variants without change.
2614
2642
fn to_and_from ( ) {
0 commit comments