Skip to content

SockaddrStorage::as_sockaddr_in incorrectly returns None sometime  #1709

@poliorcetics

Description

@poliorcetics

On nix 0.24.x the following is necessary to always manage to extract the IP address (and maybe something similar is needed for IPv6, but I have not encountered the problem

/// Converts a socket addr into an IP address when possible
fn try_into_ip_addr(s: &SockaddrStorage) -> Option<std::net::IpAddr> {
    // Normal method
    let or_else = s
        .as_sockaddr_in()
        .map(|sa| sa.ip().to_be_bytes().into())
        .or_else(|| s.as_sockaddr_in6().map(|sa| sa.ip().into()));

    // Start of the fallback
    match initial_method {
        im @ Some(_) => return im,
        None => (),
    }

    let sock_addr = unsafe { s.as_ptr().as_ref()? };
    if i32::from(sock_addr.sa_family) == nix::libc::AF_INET {
        dbg!(&s);
        let sock_addr = unsafe { *s.as_ptr().cast::<nix::libc::sockaddr_in>() };
        Some(Ipv4Addr::from(sock_addr.sin_addr.s_addr).into())
    } else {
        None
    }
}

Maybe something about the size ?

I'm on macOS 12 but CI also fails for every type of Linux we have, both GNU and MUSL

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions