Nix socket and socket2

Both nix crate and socket2 crate provides APIs for Unix socket programming. I started with socket2 but had to import nix to find all local IPs ( getifaddrs()). But it also introduces some confusion, for example both has SockAddr type.

I'm curious how others use these two crates? Do you use both at the same time? Thanks.

Usually I've just used socket2, but I also didn't need a method only in nix.

For the SockAddr case you can write helper functions:

fn nix_to_socket2(nix: nix::sys::socket::SockAddr) -> socket2::SockAddr {
    let (sockaddr, socklen) = nix.as_ffi_pair();
    unsafe { socket2::SockAddr::from_raw_parts(sockaddr, socklen) }
}
fn socket2_to_nix(socket2: socket2::SockAddr) -> nix::sys::socket::SockAddr {
    let storage = unsafe { &*(socket2.as_ptr() as *const libc::sockaddr_storage) };
    nix::sys::socket::sockaddr_storage_to_addr(storage, socket2.len() as usize).unwrap()
}

Eventually I went with nix crate only. It uses RawFd for socket abstraction but that's okay. The good thing is that it covers most of the standard socket API as it wraps libc.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.