Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restore conversions from ip v4/6 Sockaddr types to std::net equivalents. #1711

Merged
merged 1 commit into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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