43 releases

0.13.0 Dec 29, 2024
0.12.1 Oct 23, 2024
0.12.0 Sep 10, 2024
0.11.5 Jun 6, 2024
0.2.3 Oct 28, 2020

#159 in Network programming

Download history 2993/week @ 2024-09-22 2461/week @ 2024-09-29 2302/week @ 2024-10-06 2540/week @ 2024-10-13 2441/week @ 2024-10-20 3309/week @ 2024-10-27 2518/week @ 2024-11-03 1816/week @ 2024-11-10 2255/week @ 2024-11-17 1891/week @ 2024-11-24 2032/week @ 2024-12-01 2490/week @ 2024-12-08 2791/week @ 2024-12-15 988/week @ 2024-12-22 990/week @ 2024-12-29 2205/week @ 2025-01-05

7,280 downloads per month
Used in 9 crates (6 directly)

MIT/Apache

33KB
720 lines

Tokio TUN/TAP

Build crates.io Documentation examples

Asynchronous allocation of TUN/TAP devices in Rust using tokio. Use async-tun for async-std version.

Getting Started

  • Create a tun device using Tun::builder() and read from it in a loop:
#[tokio::main]
async fn main() {
    let tun = Arc::new(
        Tun::builder()
            .name("")            // if name is empty, then it is set by kernel.
            .tap()               // uses TAP instead of TUN (default).
            .packet_info()       // avoids setting IFF_NO_PI.
            .up()                // or set it up manually using `sudo ip link set <tun-name> up`.
            .build()
            .unwrap()
            .pop()
            .unwrap(),
    );

    println!("tun created, name: {}, fd: {}", tun.name(), tun.as_raw_fd());

    let (mut reader, mut _writer) = tokio::io::split(tun);

    // Writer: simply clone Arced Tun.
    let tun_c = tun.clone();
    tokio::spawn(async move{
        let buf = b"data to be written";
        tun_c.send_all(buf).await.unwrap();
    });

    // Reader
    let mut buf = [0u8; 1024];
    loop {
        let n = tun.recv(&mut buf).await.unwrap();
        println!("reading {} bytes: {:?}", n, &buf[..n]);
    }
}
  • Run the code using sudo:
sudo -E $(which cargo) run
  • Set the address of device (address and netmask could also be set using TunBuilder):
sudo ip a add 10.0.0.1/24 dev <tun-name>
  • Ping to read packets:
ping 10.0.0.2
  • Display devices and analyze the network traffic:
ip tuntap
sudo tshark -i <tun-name>

Supported Platforms

  • Linux
  • FreeBSD
  • Android
  • OSX
  • iOS
  • Windows

Examples

  • read: Split tun to (reader, writer) pair and read packets from reader.
  • read-mq: Read from multi-queue tun using tokio::select!.
sudo -E $(which cargo) run --example read
sudo -E $(which cargo) run --example read-mq

Dependencies

~4–12MB
~143K SLoC