Skip to content

Commit

Permalink
Merge #1711
Browse files Browse the repository at this point in the history
1711: Restore conversions from ip v4/6 Sockaddr types to std::net equivalents. r=asomers a=khuey

Fixes #1710

Co-authored-by: Kyle Huey <khuey@kylehuey.com>
  • Loading branch information
bors[bot] and khuey authored May 3, 2022
2 parents 4d79e93 + 024c0d7 commit 3109a6d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ This project adheres to [Semantic Versioning](https://semver.org/).

## [Unreleased] - ReleaseDate
### Added

- impl From<SockaddrIn> for std::net::SocketAddrV4 and
impl From<SockaddrIn6> for std::net::SocketAddrV6.
(#[1711](https://github.com/nix-rust/nix/pull/1711))

### Changed
### Fixed
### Removed
Expand Down
22 changes: 22 additions & 0 deletions src/sys/socket/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1233,6 +1233,16 @@ impl From<net::SocketAddrV4> for SockaddrIn {
}
}

#[cfg(feature = "net")]
impl From<SockaddrIn> 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;
Expand Down Expand Up @@ -1329,6 +1339,18 @@ impl From<net::SocketAddrV6> for SockaddrIn6 {
}
}

#[cfg(feature = "net")]
impl From<SockaddrIn6> 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;
Expand Down
13 changes: 13 additions & 0 deletions test/sys/test_socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down

0 comments on commit 3109a6d

Please sign in to comment.