pub struct SyncDevice(/* private fields */);
Expand description
A transparent wrapper around DeviceImpl, providing synchronous I/O operations.
§Examples
Basic read/write operation:
use std::net::Ipv4Addr;
use tun_rs::DeviceBuilder;
fn main() -> std::io::Result<()> {
// Create a TUN device using the builder
let mut tun = DeviceBuilder::new()
.name("my-tun")
.ipv4(Ipv4Addr::new(10, 0, 0, 1), 24, None)
.build_sync()?;
// Send a packet
// Example IP packet (Replace with real IP message)
let packet = b"[IP Packet: 10.0.0.1 -> 10.0.0.2] Hello, TUN!";
tun.send(packet)?;
println!("Sent {} bytes IP packet", packet.len());
// Receive a packet
let mut buf = [0u8; 1500];
let n = tun.recv(&mut buf)?;
println!("Received {} bytes: {:?}", n, &buf[..n]);
Ok(())
}
Implementations§
Source§impl SyncDevice
impl SyncDevice
Sourcepub unsafe fn from_fd(fd: RawFd) -> Result<Self>
pub unsafe fn from_fd(fd: RawFd) -> Result<Self>
Creates a new SyncDevice from a raw file descriptor.
§Safety
- The file descriptor (
fd
) must be an owned file descriptor. - It must be valid and open.
This function is only available on Unix platforms.
Sourcepub fn recv(&self, buf: &mut [u8]) -> Result<usize>
pub fn recv(&self, buf: &mut [u8]) -> Result<usize>
Receives data from the device into the provided buffer.
Returns the number of bytes read, or an I/O error.
§Example
use std::net::Ipv4Addr;
use tun_rs::DeviceBuilder;
let mut tun = DeviceBuilder::new()
.name("my-tun")
.ipv4(Ipv4Addr::new(10, 0, 0, 1), 24, None)
.build_sync()
.unwrap();
let mut buf = [0u8; 1500];
tun.recv(&mut buf).unwrap();
§Note
Blocking the current thread if no packet is available
Sourcepub fn send(&self, buf: &[u8]) -> Result<usize>
pub fn send(&self, buf: &[u8]) -> Result<usize>
Sends data from the provided buffer to the device.
Returns the number of bytes written, or an I/O error.
§Example
use std::net::Ipv4Addr;
use tun_rs::DeviceBuilder;
let mut tun = DeviceBuilder::new()
.name("my-tun")
.ipv4(Ipv4Addr::new(10, 0, 0, 1), 24, None)
.build_sync()
.unwrap();
tun.send(b"hello").unwrap();
pub fn shutdown(&self) -> Result<()>
Sourcepub fn recv_intr(&self, buf: &mut [u8], event: &InterruptEvent) -> Result<usize>
pub fn recv_intr(&self, buf: &mut [u8], event: &InterruptEvent) -> Result<usize>
Reads data into the provided buffer, with support for interruption.
This function attempts to read from the underlying file descriptor into buf
,
and can be interrupted using the given InterruptEvent
. If the event
is triggered
while the read operation is blocked, the function will return early with
an error of kind std::io::ErrorKind::Interrupted
.
§Arguments
buf
- The buffer to store the read data.event
- AnInterruptEvent
used to interrupt the blocking read.
§Returns
On success, returns the number of bytes read. On failure, returns an std::io::Error
.
§Platform-specific Behavior
On Unix platforms, it is recommended to use this together with set_nonblocking(true)
.
Without setting non-blocking mode, concurrent reads may not respond properly to interrupt signals.
§Feature
This method is only available when the interruptible
feature is enabled.
Sourcepub fn recv_vectored_intr(
&self,
bufs: &mut [IoSliceMut<'_>],
event: &InterruptEvent,
) -> Result<usize>
pub fn recv_vectored_intr( &self, bufs: &mut [IoSliceMut<'_>], event: &InterruptEvent, ) -> Result<usize>
pub fn wait_readable_intr(&self, event: &InterruptEvent) -> Result<()>
pub fn send_intr(&self, buf: &[u8], event: &InterruptEvent) -> Result<usize>
pub fn send_vectored_intr( &self, bufs: &[IoSlice<'_>], event: &InterruptEvent, ) -> Result<usize>
pub fn wait_writable_intr(&self, event: &InterruptEvent) -> Result<()>
Sourcepub fn recv_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
pub fn recv_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
Receives data from the device into multiple buffers using vectored I/O.
Note: This method operates on a single packet only. It will only read data from one packet, even if multiple buffers are provided.
Returns the total number of bytes read from the packet, or an error.
Sourcepub fn send_vectored(&self, bufs: &[IoSlice<'_>]) -> Result<usize>
pub fn send_vectored(&self, bufs: &[IoSlice<'_>]) -> Result<usize>
Sends data to the device from multiple buffers using vectored I/O.
Note: This method operates on a single packet only. It will only send the data contained in the provided buffers as one packet.
Returns the total number of bytes written for the packet, or an error.
Sourcepub fn is_nonblocking(&self) -> Result<bool>
pub fn is_nonblocking(&self) -> Result<bool>
Checks whether the device is currently operating in nonblocking mode.
Returns true
if nonblocking mode is enabled, false
otherwise, or an error.
Sourcepub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>
pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>
Sets the nonblocking mode for the device.
nonblocking
: Passtrue
to enable nonblocking mode,false
to disable.
Returns an empty result on success or an I/O error.
Methods from Deref<Target = DeviceImpl>§
Sourcepub fn if_index(&self) -> Result<u32>
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.
Sourcepub fn addresses(&self) -> Result<Vec<IpAddr>>
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.
Sourcepub fn set_associate_route(&self, associate_route: bool)
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.
Sourcepub fn associate_route(&self) -> bool
pub fn associate_route(&self) -> bool
Retrieve whether route is associated with the IP setting interface, see DeviceImpl::set_associate_route
Sourcepub fn mtu(&self) -> Result<u16>
pub fn mtu(&self) -> Result<u16>
Retrieves the current MTU (Maximum Transmission Unit) for the interface.
Sourcepub fn set_mtu(&self, value: u16) -> Result<()>
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.
Sourcepub fn set_network_address<IPv4: ToIpv4Address, Netmask: ToIpv4Netmask>(
&self,
address: IPv4,
netmask: Netmask,
destination: Option<IPv4>,
) -> Result<()>
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.
Sourcepub fn add_address_v4<IPv4: ToIpv4Address, Netmask: ToIpv4Netmask>(
&self,
address: IPv4,
netmask: Netmask,
) -> Result<()>
pub fn add_address_v4<IPv4: ToIpv4Address, Netmask: ToIpv4Netmask>( &self, address: IPv4, netmask: Netmask, ) -> Result<()>
Add IPv4 network address, netmask
Sourcepub fn remove_address(&self, addr: IpAddr) -> Result<()>
pub fn remove_address(&self, addr: IpAddr) -> Result<()>
Removes an IP address from the interface.
Sourcepub fn add_address_v6<IPv6: ToIpv6Address, Netmask: ToIpv6Netmask>(
&self,
addr: IPv6,
netmask: Netmask,
) -> Result<()>
pub fn add_address_v6<IPv6: ToIpv6Address, Netmask: ToIpv6Netmask>( &self, addr: IPv6, netmask: Netmask, ) -> Result<()>
Adds an IPv6 address to the interface.
Sourcepub fn set_mac_address(&self, eth_addr: [u8; 6]) -> Result<()>
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.
Sourcepub fn mac_address(&self) -> Result<[u8; 6]>
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.
Sourcepub fn enable_tunsifhead(&self) -> Result<()>
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.
Sourcepub fn ignore_packet_info(&self) -> bool
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
.
Sourcepub fn set_ignore_packet_info(&self, ign: bool)
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.
- If
§Note
This only works for a TUN device; The invocation will be ignored if the device is a TAP.
Trait Implementations§
Source§impl AsFd for SyncDevice
impl AsFd for SyncDevice
Source§fn as_fd(&self) -> BorrowedFd<'_>
fn as_fd(&self) -> BorrowedFd<'_>
Source§impl AsRawFd for SyncDevice
impl AsRawFd for SyncDevice
Source§impl Deref for SyncDevice
impl Deref for SyncDevice
Source§impl FromRawFd for SyncDevice
impl FromRawFd for SyncDevice
Source§unsafe fn from_raw_fd(fd: RawFd) -> Self
unsafe fn from_raw_fd(fd: RawFd) -> Self
Self
from the given raw file
descriptor. Read more