Skip to content

Commit 024c0d7

Browse files
committed
Restore conversions from ip v4/6 Sockaddr types to std::net equivalents.
Fixes #1710
1 parent 4d79e93 commit 024c0d7

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ This project adheres to [Semantic Versioning](https://semver.org/).
55

66
## [Unreleased] - ReleaseDate
77
### Added
8+
9+
- impl From<SockaddrIn> for std::net::SocketAddrV4 and
10+
impl From<SockaddrIn6> for std::net::SocketAddrV6.
11+
(#[1711](https://github.com/nix-rust/nix/pull/1711))
12+
813
### Changed
914
### Fixed
1015
### Removed

src/sys/socket/addr.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1233,6 +1233,16 @@ impl From<net::SocketAddrV4> for SockaddrIn {
12331233
}
12341234
}
12351235

1236+
#[cfg(feature = "net")]
1237+
impl From<SockaddrIn> for net::SocketAddrV4 {
1238+
fn from(addr: SockaddrIn) -> Self {
1239+
net::SocketAddrV4::new(
1240+
net::Ipv4Addr::from(addr.0.sin_addr.s_addr.to_ne_bytes()),
1241+
u16::from_be(addr.0.sin_port)
1242+
)
1243+
}
1244+
}
1245+
12361246
#[cfg(feature = "net")]
12371247
impl std::str::FromStr for SockaddrIn {
12381248
type Err = net::AddrParseError;
@@ -1329,6 +1339,18 @@ impl From<net::SocketAddrV6> for SockaddrIn6 {
13291339
}
13301340
}
13311341

1342+
#[cfg(feature = "net")]
1343+
impl From<SockaddrIn6> for net::SocketAddrV6 {
1344+
fn from(addr: SockaddrIn6) -> Self {
1345+
net::SocketAddrV6::new(
1346+
net::Ipv6Addr::from(addr.0.sin6_addr.s6_addr),
1347+
u16::from_be(addr.0.sin6_port),
1348+
u32::from_be(addr.0.sin6_flowinfo),
1349+
u32::from_be(addr.0.sin6_scope_id)
1350+
)
1351+
}
1352+
}
1353+
13321354
#[cfg(feature = "net")]
13331355
impl std::str::FromStr for SockaddrIn6 {
13341356
type Err = net::AddrParseError;

test/sys/test_socket.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,19 @@ pub fn test_socketpair() {
257257
assert_eq!(&buf[..], b"hello");
258258
}
259259

260+
#[test]
261+
pub fn test_std_conversions() {
262+
use nix::sys::socket::*;
263+
264+
let std_sa = SocketAddrV4::from_str("127.0.0.1:6789").unwrap();
265+
let sock_addr = SockaddrIn::from(std_sa);
266+
assert_eq!(std_sa, sock_addr.into());
267+
268+
let std_sa = SocketAddrV6::from_str("[::1]:6000").unwrap();
269+
let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa);
270+
assert_eq!(std_sa, sock_addr.into());
271+
}
272+
260273
mod recvfrom {
261274
use nix::Result;
262275
use nix::sys::socket::*;

0 commit comments

Comments
 (0)