Struct socket2::sockaddr::SockAddr

source ·
pub struct SockAddr {
    storage: sockaddr_storage,
    len: socklen_t,
}
Expand description

The address of a socket.

SockAddrs may be constructed directly to and from the standard library SocketAddr, SocketAddrV4, and SocketAddrV6 types.

Fields§

§storage: sockaddr_storage§len: socklen_t

Implementations§

source§

impl SockAddr

source

pub const unsafe fn new(storage: sockaddr_storage, len: socklen_t) -> SockAddr

Create a SockAddr from the underlying storage and its length.

§Safety

Caller must ensure that the address family and length match the type of storage address. For example if storage.ss_family is set to AF_INET the storage must be initialised as sockaddr_in, setting the content and length appropriately.

§Examples
use std::io;
use std::mem;
use std::os::unix::io::AsRawFd;

use socket2::{SockAddr, Socket, Domain, Type};

let socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;

// Initialise a `SocketAddr` byte calling `getsockname(2)`.
let mut addr_storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
let mut len = mem::size_of_val(&addr_storage) as libc::socklen_t;

// The `getsockname(2)` system call will intiliase `storage` for
// us, setting `len` to the correct length.
let res = unsafe {
    libc::getsockname(
        socket.as_raw_fd(),
        (&mut addr_storage as *mut libc::sockaddr_storage).cast(),
        &mut len,
    )
};
if res == -1 {
    return Err(io::Error::last_os_error());
}

let address = unsafe { SockAddr::new(addr_storage, len) };
source

pub unsafe fn try_init<F, T>(init: F) -> Result<(T, SockAddr)>

Initialise a SockAddr by calling the function init.

The type of the address storage and length passed to the function init is OS/architecture specific.

The address is zeroed before init is called and is thus valid to dereference and read from. The length initialised to the maximum length of the storage.

§Safety

Caller must ensure that the address family and length match the type of storage address. For example if storage.ss_family is set to AF_INET the storage must be initialised as sockaddr_in, setting the content and length appropriately.

§Examples
use std::io;
use std::os::unix::io::AsRawFd;

use socket2::{SockAddr, Socket, Domain, Type};

let socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;

// Initialise a `SocketAddr` byte calling `getsockname(2)`.
let (_, address) = unsafe {
    SockAddr::try_init(|addr_storage, len| {
        // The `getsockname(2)` system call will intiliase `storage` for
        // us, setting `len` to the correct length.
        if libc::getsockname(socket.as_raw_fd(), addr_storage.cast(), len) == -1 {
            Err(io::Error::last_os_error())
        } else {
            Ok(())
        }
    })
}?;
source

pub fn unix<P>(path: P) -> Result<SockAddr>
where P: AsRef<Path>,

Constructs a SockAddr with the family AF_UNIX and the provided path.

Returns an error if the path is longer than SUN_LEN.

source

pub unsafe fn set_length(&mut self, length: socklen_t)

Set the length of the address.

§Safety

Caller must ensure that the address up to length bytes are properly initialised.

source

pub const fn family(&self) -> sa_family_t

Returns this address’s family.

source

pub const fn domain(&self) -> Domain

Returns this address’s Domain.

source

pub const fn len(&self) -> socklen_t

Returns the size of this address in bytes.

source

pub const fn as_ptr(&self) -> *const sockaddr

Returns a raw pointer to the address.

source

pub const fn as_storage(self) -> sockaddr_storage

Retuns the address as the storage.

source

pub const fn is_ipv4(&self) -> bool

Returns true if this address is in the AF_INET (IPv4) family, false otherwise.

source

pub const fn is_ipv6(&self) -> bool

Returns true if this address is in the AF_INET6 (IPv6) family, false otherwise.

source

pub fn is_unix(&self) -> bool

Returns true if this address is of a unix socket (for local interprocess communication), i.e. it is from the AF_UNIX family, false otherwise.

source

pub fn as_socket(&self) -> Option<SocketAddr>

Returns this address as a SocketAddr if it is in the AF_INET (IPv4) or AF_INET6 (IPv6) family, otherwise returns None.

source

pub fn as_socket_ipv4(&self) -> Option<SocketAddrV4>

Returns this address as a SocketAddrV4 if it is in the AF_INET family.

source

pub fn as_socket_ipv6(&self) -> Option<SocketAddrV6>

Returns this address as a SocketAddrV6 if it is in the AF_INET6 family.

source

fn as_bytes(&self) -> &[u8]

Returns the initialised storage bytes.

source§

impl SockAddr

Unix only API.

source

pub fn vsock(cid: u32, port: u32) -> SockAddr

Constructs a SockAddr with the family AF_VSOCK and the provided CID/port.

§Errors

This function can never fail. In a future version of this library it will be made infallible.

source

pub fn as_vsock_address(&self) -> Option<(u32, u32)>

Returns this address VSOCK CID/port if it is in the AF_VSOCK family, otherwise return None.

source

pub fn is_unnamed(&self) -> bool

Returns true if this address is an unnamed address from the AF_UNIX family (for local interprocess communication), false otherwise.

source

pub(crate) fn as_sockaddr_un(&self) -> Option<&sockaddr_un>

Returns the underlying sockaddr_un object if this addres is from the AF_UNIX family, otherwise returns None.

source

fn path_len(&self, storage: &sockaddr_un) -> usize

Get the length of the path bytes of the address, not including the terminating or initial (for abstract names) null byte.

Should not be called on unnamed addresses.

source

fn path_bytes(&self, storage: &sockaddr_un, abstract_name: bool) -> &[u8]

Get a u8 slice for the bytes of the pathname or abstract name.

Should not be called on unnamed addresses.

source

pub fn as_unix(&self) -> Option<SocketAddr>

Returns this address as Unix SocketAddr if it is an AF_UNIX pathname address, otherwise returns None.

source

pub fn as_pathname(&self) -> Option<&Path>

Returns this address as a Path reference if it is an AF_UNIX pathname address, otherwise returns None.

source

pub fn as_abstract_namespace(&self) -> Option<&[u8]>

Returns this address as a slice of bytes representing an abstract address if it is an AF_UNIX abstract address, otherwise returns None.

Abstract addresses are a Linux extension, so this method returns None on all non-Linux platforms.

Trait Implementations§

source§

impl Clone for SockAddr

source§

fn clone(&self) -> SockAddr

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for SockAddr

source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<SocketAddr> for SockAddr

source§

fn from(addr: SocketAddr) -> SockAddr

Converts to this type from the input type.
source§

impl From<SocketAddrV4> for SockAddr

source§

fn from(addr: SocketAddrV4) -> SockAddr

Converts to this type from the input type.
source§

impl From<SocketAddrV6> for SockAddr

source§

fn from(addr: SocketAddrV6) -> SockAddr

Converts to this type from the input type.
source§

impl Hash for SockAddr

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for SockAddr

source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Eq for SockAddr

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.