diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e79d37a57..8e9baf9005 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ This project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] - ReleaseDate ### Added + +- impl From for std::net::SocketAddrV4 and + impl From for std::net::SocketAddrV6. + (#[1711](https://github.com/nix-rust/nix/pull/1711)) + ### Changed ### Fixed ### Removed diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 52d60ac9ab..5cd4678c3c 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -1233,6 +1233,16 @@ impl From for SockaddrIn { } } +#[cfg(feature = "net")] +impl From for net::SocketAddrV4 { + fn from(addr: SockaddrIn) -> Self { + net::SocketAddrV4::new( + net::Ipv4Addr::from(addr.0.sin_addr.s_addr.to_ne_bytes()), + u16::from_be(addr.0.sin_port) + ) + } +} + #[cfg(feature = "net")] impl std::str::FromStr for SockaddrIn { type Err = net::AddrParseError; @@ -1329,6 +1339,18 @@ impl From for SockaddrIn6 { } } +#[cfg(feature = "net")] +impl From for net::SocketAddrV6 { + fn from(addr: SockaddrIn6) -> Self { + net::SocketAddrV6::new( + net::Ipv6Addr::from(addr.0.sin6_addr.s6_addr), + u16::from_be(addr.0.sin6_port), + u32::from_be(addr.0.sin6_flowinfo), + u32::from_be(addr.0.sin6_scope_id) + ) + } +} + #[cfg(feature = "net")] impl std::str::FromStr for SockaddrIn6 { type Err = net::AddrParseError; diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 2aac795851..c742960ae8 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -257,6 +257,19 @@ pub fn test_socketpair() { assert_eq!(&buf[..], b"hello"); } +#[test] +pub fn test_std_conversions() { + use nix::sys::socket::*; + + let std_sa = SocketAddrV4::from_str("127.0.0.1:6789").unwrap(); + let sock_addr = SockaddrIn::from(std_sa); + assert_eq!(std_sa, sock_addr.into()); + + let std_sa = SocketAddrV6::from_str("[::1]:6000").unwrap(); + let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa); + assert_eq!(std_sa, sock_addr.into()); +} + mod recvfrom { use nix::Result; use nix::sys::socket::*;