nix icon indicating copy to clipboard operation
nix copied to clipboard

`self.len() >= mem::size_of::<libc::sockaddr_dl>() as libc::socklen_t` on netbsd is `false`

Open xmh0511 opened this issue 4 months ago • 2 comments

    ///   Safely and falliably downcast to an immutable reference 
    pub fn as_link_addr(&self) -> Option<&LinkAddr> {
        if self.family() == Some(AddressFamily::Link)
            && self.len() >= mem::size_of::<libc::sockaddr_dl>() as libc::socklen_t
        {
            Some(unsafe { &self.dl })
        } else {
            None
        }
    }

On NetBSD, the condition self.len() >= mem::size_of::<libc::sockaddr_dl>() as libc::socklen_t is false, which results in println!("{}",addr) can print the correct result but addr.as_link_addr() is always None.

The test code is:

use std::mem;
#[cfg(any(bsd, linux_android, target_os = "illumos"))]
fn main() {
    use nix::ifaddrs::getifaddrs;
    use nix::sys::socket::{SockaddrLike, SockaddrStorage};

    let addrs = getifaddrs().unwrap();
    let addrs = addrs.filter(|item| item.interface_name == "tap0".to_string());
    for addr in addrs {
        let family = addr
            .address
            .as_ref()
            .and_then(SockaddrStorage::family)
            .map(|af| format!("{af:?}"))
            .unwrap_or("".to_owned());
        if family == "Link"{
           let addr = addr.address.unwrap();
           println!("addr {}",addr);
           println!("{:?}, condition :{} len: {}, type size {}",addr.as_link_addr(), addr.len() >= mem::size_of::<libc::sockaddr_dl>() as libc::socklen_t,addr.len(),mem::size_of::<libc::sockaddr_dl>() as libc::socklen_t);
        }       
    }    
}

the output is:

# cargo run --example getifaddrs --features="net"
   Compiling nix v0.30.1 (/projects/nix-master)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.65s
     Running `/projects/nix-master/target/debug/examples/getifaddrs`
addr f2:0b:a4:42:f4:41
None, condition :false len: 18, type size 20

xmh0511 avatar Aug 18 '25 06:08 xmh0511

What is the Self type in your example? Why is the sa_len field too small? Is sockaddr_dl not the right struct to use on NetBSD?

asomers avatar Aug 18 '25 14:08 asomers

What is the Self type in your example?

The type of Self is SockaddrStorage.

Is sockaddr_dl not the right struct to use on NetBSD?

This is the inner implementation of as_link_addr, see https://docs.rs/nix/0.30.1/src/nix/sys/socket/addr.rs.html#1354-1356 and https://docs.rs/nix/0.30.1/src/nix/sys/socket/addr.rs.html#1262

xmh0511 avatar Aug 19 '25 01:08 xmh0511