nix::sys::socket

Trait SockaddrLike

source
pub trait SockaddrLike: SockaddrLikePriv {
    // Required method
    unsafe fn from_raw(
        addr: *const sockaddr,
        len: Option<socklen_t>,
    ) -> Option<Self>
       where Self: Sized;

    // Provided methods
    fn as_ptr(&self) -> *const sockaddr { ... }
    fn family(&self) -> Option<AddressFamily> { ... }
    fn len(&self) -> socklen_t { ... }
    fn size() -> socklen_t
       where Self: Sized { ... }
}
Expand description

Anything that, in C, can be cast back and forth to sockaddr.

Most implementors also implement AsRef<libc::XXX> to access their inner type read-only.

Required Methods§

source

unsafe fn from_raw( addr: *const sockaddr, len: Option<socklen_t>, ) -> Option<Self>
where Self: Sized,

Unsafe constructor from a variable length source

Some C APIs from provide len, and others do not. If it’s provided it will be validated. If not, it will be guessed based on the family.

§Arguments
  • addr: raw pointer to something that can be cast to a libc::sockaddr. For example, libc::sockaddr_in, libc::sockaddr_in6, etc.
  • len: For fixed-width types like sockaddr_in, it will be validated if present and ignored if not. For variable-width types it is required and must be the total length of valid data. For example, if addr points to a named sockaddr_un, then len must be the length of the structure up to but not including the trailing NUL.
§Safety

addr must be valid for the specific type of sockaddr. len, if present, must not exceed the length of valid data in addr.

Provided Methods§

source

fn as_ptr(&self) -> *const sockaddr

Returns a raw pointer to the inner structure. Useful for FFI.

source

fn family(&self) -> Option<AddressFamily>

Return the address family of this socket

§Examples

One common use is to match on the family of a union type, like this:

let fd = socket(AddressFamily::Inet, SockType::Stream,
    SockFlag::empty(), None).unwrap();
let ss: SockaddrStorage = getsockname(fd.as_raw_fd()).unwrap();
match ss.family().unwrap() {
    AddressFamily::Inet => println!("{}", ss.as_sockaddr_in().unwrap()),
    AddressFamily::Inet6 => println!("{}", ss.as_sockaddr_in6().unwrap()),
    _ => println!("Unexpected address family")
}
source

fn len(&self) -> socklen_t

Return the length of valid data in the sockaddr structure.

For fixed-size sockaddrs, this should be the size of the structure. But for variable-sized types like UnixAddr it may be less.

source

fn size() -> socklen_t
where Self: Sized,

Return the available space in the structure

Implementations on Foreign Types§

source§

impl SockaddrLike for ()

() can be used in place of a real Sockaddr when no address is expected, for example for a field of Option<S> where S: SockaddrLike.

Implementors§