Struct netlink_sys::Socket

source ·
pub struct Socket(/* private fields */);
Expand description

A netlink socket.

§Example

In this example we:

  1. open a new socket
  2. send a message to the kernel
  3. read the reponse
use netlink_sys::{protocols::NETLINK_ROUTE, Socket, SocketAddr};
use std::process;

// open a new socket for the NETLINK_ROUTE subsystem (see "man 7 rtnetlink")
let mut socket = Socket::new(NETLINK_ROUTE).unwrap();
// address of the remote peer we'll send a message to. This particular address is for the kernel
let kernel_addr = SocketAddr::new(0, 0);
// this is a valid message for listing the network links on the system
let pkt = vec![
    0x14, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x03, 0xfd, 0xfe, 0x38, 0x5c, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00,
];
// send the message to the kernel
let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap();
assert_eq!(n_sent, pkt.len());
// buffer for receiving the response
let mut buf = vec![0; 4096];
loop {
    // receive a datagram
    let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap();
    assert_eq!(sender_addr, kernel_addr);
    println!("received datagram {:?}", &buf[..n_received]);
    if buf[4] == 2 && buf[5] == 0 {
        println!("the kernel responded with an error");
        return;
    }
    if buf[4] == 3 && buf[5] == 0 {
        println!("end of dump");
        return;
    }
}

Implementations§

source§

impl Socket

source

pub fn new(protocol: isize) -> Result<Self>

Open a new socket for the given netlink subsystem. protocol must be one of the netlink_sys::protocols constants.

source

pub fn bind(&mut self, addr: &SocketAddr) -> Result<()>

Bind the socket to the given address

source

pub fn bind_auto(&mut self) -> Result<SocketAddr>

Bind the socket to an address assigned by the kernel, and return that address.

source

pub fn get_address(&self, addr: &mut SocketAddr) -> Result<()>

Get the socket address

source

pub fn set_non_blocking(&self, non_blocking: bool) -> Result<()>

Make this socket non-blocking

source

pub fn connect(&self, remote_addr: &SocketAddr) -> Result<()>

Connect the socket to the given address. Netlink is a connection-less protocol, so a socket can communicate with multiple peers with the Socket::send_to and Socket::recv_from methods. However, if the socket only needs to communicate with one peer, it is convenient not to have to bother with the peer address. This is what connect is for. After calling connect, Socket::send and Socket::recv respectively send and receive datagrams to and from remote_addr.

§Examples

In this example we:

  1. open a socket
  2. connect it to the kernel with Socket::connect
  3. send a request to the kernel with Socket::send
  4. read the response (which can span over several messages) Socket::recv
use netlink_sys::{protocols::NETLINK_ROUTE, Socket, SocketAddr};
use std::process;

let mut socket = Socket::new(NETLINK_ROUTE).unwrap();
let _ = socket.bind_auto().unwrap();
let kernel_addr = SocketAddr::new(0, 0);
socket.connect(&kernel_addr).unwrap();
// This is a valid message for listing the network links on the system
let msg = vec![
    0x14, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x03, 0xfd, 0xfe, 0x38, 0x5c, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00,
];
let n_sent = socket.send(&msg[..], 0).unwrap();
assert_eq!(n_sent, msg.len());
// buffer for receiving the response
let mut buf = vec![0; 4096];
loop {
    let mut n_received = socket.recv(&mut &mut buf[..], 0).unwrap();
    println!("received {:?}", &buf[..n_received]);
    if buf[4] == 2 && buf[5] == 0 {
        println!("the kernel responded with an error");
        return;
    }
    if buf[4] == 3 && buf[5] == 0 {
        println!("end of dump");
        return;
    }
}
source

pub fn recv_from<B>( &self, buf: &mut B, flags: c_int ) -> Result<(usize, SocketAddr)>
where B: BufMut,

Read a datagram from the socket and return the number of bytes that have been read and the address of the sender. The data being read is copied into buf. If buf is too small, the datagram is truncated. The supported flags are the MSG_* described in man 2 recvmsg

§Warning

In datagram oriented protocols, recv and recvfrom receive normally only ONE datagram, but this seems not to be always true for netlink sockets: with some protocols like NETLINK_AUDIT, multiple netlink packets can be read with a single call.

source

pub fn recv<B>(&self, buf: &mut B, flags: c_int) -> Result<usize>
where B: BufMut,

For a connected socket, recv reads a datagram from the socket. The sender is the remote peer the socket is connected to (see Socket::connect). See also Socket::recv_from

source

pub fn recv_from_full(&self) -> Result<(Vec<u8>, SocketAddr)>

Receive a full message. Unlike Socket::recv_from, which truncates messages that exceed the length of the buffer passed as argument, this method always reads a whole message, no matter its size.

source

pub fn send_to( &self, buf: &[u8], addr: &SocketAddr, flags: c_int ) -> Result<usize>

Send the given buffer buf to the remote peer with address addr. The supported flags are the MSG_* values documented in man 2 send.

source

pub fn send(&self, buf: &[u8], flags: c_int) -> Result<usize>

For a connected socket, send sends the given buffer buf to the remote peer the socket is connected to. See also Socket::connect and Socket::send_to.

source

pub fn set_pktinfo(&mut self, value: bool) -> Result<()>

source

pub fn get_pktinfo(&self) -> Result<bool>

source

pub fn add_membership(&mut self, group: u32) -> Result<()>

source

pub fn drop_membership(&mut self, group: u32) -> Result<()>

source

pub fn set_broadcast_error(&mut self, value: bool) -> Result<()>

NETLINK_BROADCAST_ERROR (since Linux 2.6.30). When not set, netlink_broadcast() only reports ESRCH errors and silently ignore NOBUFS errors.

source

pub fn get_broadcast_error(&self) -> Result<bool>

source

pub fn set_no_enobufs(&mut self, value: bool) -> Result<()>

NETLINK_NO_ENOBUFS (since Linux 2.6.30). This flag can be used by unicast and broadcast listeners to avoid receiving ENOBUFS errors.

source

pub fn get_no_enobufs(&self) -> Result<bool>

source

pub fn set_listen_all_namespaces(&mut self, value: bool) -> Result<()>

NETLINK_LISTEN_ALL_NSID (since Linux 4.2). When set, this socket will receive netlink notifications from all network namespaces that have an nsid assigned into the network namespace where the socket has been opened. The nsid is sent to user space via an ancillary data.

source

pub fn get_listen_all_namespaces(&self) -> Result<bool>

source

pub fn set_cap_ack(&mut self, value: bool) -> Result<()>

NETLINK_CAP_ACK (since Linux 4.2). The kernel may fail to allocate the necessary room for the acknowledgment message back to user space. This option trims off the payload of the original netlink message. The netlink message header is still included, so the user can guess from the sequence number which message triggered the acknowledgment.

source

pub fn get_cap_ack(&self) -> Result<bool>

source

pub fn set_ext_ack(&mut self, value: bool) -> Result<()>

NETLINK_EXT_ACK Extended ACK controls reporting of additional error/warning TLVs in NLMSG_ERROR and NLMSG_DONE messages.

source

pub fn get_ext_ack(&self) -> Result<bool>

source

pub fn set_rx_buf_sz<T>(&self, size: T) -> Result<()>

Sets socket receive buffer in bytes. The kernel doubles this value (to allow space for bookkeeping overhead), and this doubled value is returned by [get_rx_buf_sz].(see socket(7) The default value is set by the proc/sys/net/core/rmem_default file, and the maximum allowed value is set by the /proc/sys/net/core/rmem_max file. The minimum (doubled) value for this option is 256.

source

pub fn get_rx_buf_sz(&self) -> Result<usize>

Gets socket receive buffer in bytes

Set strict input checking(NETLINK_GET_STRICT_CHK) in netlink route protocol. By default, NETLINK_GET_STRICT_CHK is not enabled.

Trait Implementations§

source§

impl AsRawFd for Socket

source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
source§

impl Clone for Socket

source§

fn clone(&self) -> Socket

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 Socket

source§

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

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

impl Drop for Socket

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl FromRawFd for Socket

source§

unsafe fn from_raw_fd(fd: RawFd) -> Self

Constructs a new instance of Self from the given raw file descriptor. Read more

Auto Trait Implementations§

§

impl Freeze for Socket

§

impl RefUnwindSafe for Socket

§

impl Send for Socket

§

impl Sync for Socket

§

impl Unpin for Socket

§

impl UnwindSafe for Socket

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> 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,

§

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>,

§

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>,

§

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.