AsyncDevice

Struct AsyncDevice 

Source
pub struct AsyncDevice(/* private fields */);
Available on crate features async_io or async_tokio only.
Expand description

An async Tun/Tap device wrapper around a Tun/Tap device.

This type does not provide a split method, because this functionality can be achieved by instead wrapping the socket in an Arc.

§Streams

If you need to produce a Stream, you can look at DeviceFramed.

Note: DeviceFramed is only available when the async_framed feature is enabled.

§Examples

use tun_rs::{AsyncDevice, DeviceBuilder};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    // Create a TUN device with basic configuration
    let dev = DeviceBuilder::new()
        .name("tun0")
        .mtu(1500)
        .ipv4("10.0.0.1", "255.255.255.0", None)
        .build_async()?;

    // Send a simple packet (Replace with real IP message)
    let packet = b"[IP Packet: 10.0.0.1 -> 10.0.0.2] Hello, Async TUN!";
    dev.send(packet).await?;

    // Receive a packet
    let mut buf = [0u8; 1500];
    let n = dev.recv(&mut buf).await?;
    println!("Received {} bytes: {:?}", n, &buf[..n]);

    Ok(())
}

Implementations§

Source§

impl AsyncDevice

Source

pub fn poll_readable(&self, cx: &mut Context<'_>) -> Poll<Result<()>>

Polls the I/O handle for readability.

§Caveats

Note that on multiple calls to a poll_* method in the recv direction, only the Waker from the Context passed to the most recent call will be scheduled to receive a wakeup.

§Return value

The function returns:

  • Poll::Pending if the device is not ready for reading.
  • Poll::Ready(Ok(())) if the device is ready for reading.
  • Poll::Ready(Err(e)) if an error is encountered.
§Errors

This function may encounter any standard I/O error except WouldBlock.

Source

pub fn poll_recv( &self, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize>>

Attempts to receive a single packet from the device

§Caveats

Note that on multiple calls to a poll_* method in the recv direction, only the Waker from the Context passed to the most recent call will be scheduled to receive a wakeup.

§Return value

The function returns:

  • Poll::Pending if the device is not ready to read
  • Poll::Ready(Ok(())) reads data buf if the device is ready
  • Poll::Ready(Err(e)) if an error is encountered.
§Errors

This function may encounter any standard I/O error except WouldBlock.

Source

pub fn poll_writable(&self, cx: &mut Context<'_>) -> Poll<Result<()>>

Polls the I/O handle for writability.

§Caveats

Note that on multiple calls to a poll_* method in the send direction, only the Waker from the Context passed to the most recent call will be scheduled to receive a wakeup.

§Return value

The function returns:

  • Poll::Pending if the device is not ready for writing.
  • Poll::Ready(Ok(())) if the device is ready for writing.
  • Poll::Ready(Err(e)) if an error is encountered.
§Errors

This function may encounter any standard I/O error except WouldBlock.

Source

pub fn poll_send(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>>

Attempts to send packet to the device

§Caveats

Note that on multiple calls to a poll_* method in the send direction, only the Waker from the Context passed to the most recent call will be scheduled to receive a wakeup.

§Return value

The function returns:

  • Poll::Pending if the device is not available to write
  • Poll::Ready(Ok(n)) n is the number of bytes sent
  • Poll::Ready(Err(e)) if an error is encountered.
§Errors

This function may encounter any standard I/O error except WouldBlock.

Source§

impl AsyncDevice

Source

pub fn new(device: SyncDevice) -> Result<AsyncDevice>

Source

pub unsafe fn from_fd(fd: RawFd) -> Result<AsyncDevice>

§Safety

This method is safe if the provided fd is valid Construct a AsyncDevice from an existing file descriptor

Source

pub fn into_fd(self) -> Result<RawFd>

Source

pub async fn readable(&self) -> Result<()>

Waits for the device to become readable.

This function is usually paired with try_recv().

The function may complete without the device being readable. This is a false-positive and attempting a try_recv() will return with io::ErrorKind::WouldBlock.

§Cancel safety

This method is cancel safe. Once a readiness event occurs, the method will continue to return immediately until the readiness event is consumed by an attempt to read that fails with WouldBlock or Poll::Pending.

Source

pub async fn writable(&self) -> Result<()>

Waits for the device to become writable.

This function is usually paired with try_send().

The function may complete without the device being writable. This is a false-positive and attempting a try_send() will return with io::ErrorKind::WouldBlock.

§Cancel safety

This method is cancel safe. Once a readiness event occurs, the method will continue to return immediately until the readiness event is consumed by an attempt to write that fails with WouldBlock or Poll::Pending.

Source

pub async fn recv(&self, buf: &mut [u8]) -> Result<usize>

Receives a single packet from the device. On success, returns the number of bytes read.

The function must be called with valid byte array buf of sufficient size to hold the message bytes. If a message is too long to fit in the supplied buffer, excess bytes may be discarded.

Source

pub fn try_recv(&self, buf: &mut [u8]) -> Result<usize>

Tries to receive a single packet from the device. On success, returns the number of bytes read.

This method must be called with valid byte array buf of sufficient size to hold the message bytes. If a message is too long to fit in the supplied buffer, excess bytes may be discarded.

When there is no pending data, Err(io::ErrorKind::WouldBlock) is returned. This function is usually paired with readable().

Source

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

Send a packet to the device

§Return

On success, the number of bytes sent is returned, otherwise, the encountered error is returned.

Source

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

Tries to send packet to the device.

When the device buffer is full, Err(io::ErrorKind::WouldBlock) is returned. This function is usually paired with writable().

§Returns

If successful, Ok(n) is returned, where n is the number of bytes sent. If the device is not ready to send data, Err(ErrorKind::WouldBlock) is returned.

Source

pub async fn recv_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>

Receives a packet into multiple buffers (scatter read). Processes single packet per call.

Source

pub fn try_recv_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>

Non-blocking version of recv_vectored.

Source

pub async fn send_vectored(&self, bufs: &[IoSlice<'_>]) -> Result<usize>

Sends multiple buffers as a single packet (gather write).

Source

pub fn try_send_vectored(&self, bufs: &[IoSlice<'_>]) -> Result<usize>

Non-blocking version of send_vectored.

Methods from Deref<Target = DeviceImpl>§

Source

pub fn if_index(&self) -> Result<u32>

Retrieves the interface index for the network interface.

This function converts the interface name (obtained via self.name()) into a C-compatible string (CString) and then calls the libc function if_nametoindex to retrieve the corresponding interface index.

Source

pub fn addresses(&self) -> Result<Vec<IpAddr>>

Retrieves all IP addresses associated with the network interface.

This function calls getifaddrs with the interface name, then iterates over the returned list of interface addresses, extracting and collecting the IP addresses into a vector.

Source

pub fn name(&self) -> Result<String>

Retrieves the name of the network interface.

Source

pub fn set_associate_route(&self, associate_route: bool)

If false, the program will not modify or manage routes in any way, allowing the system to handle all routing natively. If true (default), the program will automatically add or remove routes to provide consistent routing behavior across all platforms. Set this to be false to obtain the platform’s default routing behavior.

Source

pub fn associate_route(&self) -> bool

Retrieve whether route is associated with the IP setting interface, see DeviceImpl::set_associate_route

Source

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

Enables or disables the network interface.

Source

pub fn mtu(&self) -> Result<u16>

Retrieves the current MTU (Maximum Transmission Unit) for the interface.

Source

pub fn set_mtu(&self, value: u16) -> Result<()>

Sets the MTU (Maximum Transmission Unit) for the interface.

§Note

The specified value must be less than or equal to 1500; it’s a limitation of NetBSD.

Source

pub fn set_network_address<IPv4: ToIpv4Address, Netmask: ToIpv4Netmask>( &self, address: IPv4, netmask: Netmask, destination: Option<IPv4>, ) -> Result<()>

Sets the IPv4 network address, netmask, and an optional destination address. Remove all previous set IPv4 addresses and set the specified address.

Source

pub fn add_address_v4<IPv4: ToIpv4Address, Netmask: ToIpv4Netmask>( &self, address: IPv4, netmask: Netmask, ) -> Result<()>

Add IPv4 network address, netmask

Source

pub fn remove_address(&self, addr: IpAddr) -> Result<()>

Removes an IP address from the interface.

Source

pub fn add_address_v6<IPv6: ToIpv6Address, Netmask: ToIpv6Netmask>( &self, addr: IPv6, netmask: Netmask, ) -> Result<()>

Adds an IPv6 address to the interface.

Source

pub fn set_mac_address(&self, eth_addr: [u8; 6]) -> Result<()>

Sets the MAC (hardware) address for the interface.

This function constructs an interface request and copies the provided MAC address into the hardware address field. It then applies the change via a system call. This operation is typically supported only for TAP devices.

Source

pub fn mac_address(&self) -> Result<[u8; 6]>

Retrieves the MAC (hardware) address of the interface.

This function queries the MAC address by the interface name using a helper function. An error is returned if the MAC address cannot be found.

Source

pub fn enable_tunsifhead(&self) -> Result<()>

In Layer3(i.e. TUN mode), we need to put the tun interface into “multi_af” mode, which will prepend the address family to all packets (same as FreeBSD). If this is not enabled, the kernel silently drops all IPv6 packets on output and gets confused on input.

Source

pub fn ignore_packet_info(&self) -> bool

Returns whether the TUN device is set to ignore packet information (PI).

When enabled, the device does not prepend the struct tun_pi header to packets, which can simplify packet processing in some cases.

§Returns
  • true - The TUN device ignores packet information.
  • false - The TUN device includes packet information.
§Note

Retrieve whether the packet is ignored for the TUN Device; The TAP device always returns false.

Source

pub fn set_ignore_packet_info(&self, ign: bool)

Sets whether the TUN device should ignore packet information (PI).

When ignore_packet_info is set to true, the TUN device does not prepend the struct tun_pi header to packets. This can be useful if the additional metadata is not needed.

§Parameters
  • ign
    • If true, the TUN device will ignore packet information.
    • If false, it will include packet information.
§Note

This only works for a TUN device; The invocation will be ignored if the device is a TAP.

Trait Implementations§

Source§

impl AsRawFd for AsyncDevice

Source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
Source§

impl Deref for AsyncDevice

Source§

type Target = DeviceImpl

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl FromRawFd for AsyncDevice

Source§

unsafe fn from_raw_fd(fd: RawFd) -> Self

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

impl IntoRawFd for AsyncDevice

Source§

fn into_raw_fd(self) -> RawFd

Consumes this object, returning the raw underlying file descriptor. Read more

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> 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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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.