39 releases (10 breaking)

0.11.4 Apr 7, 2024
0.11.2 Oct 29, 2023
0.9.0 Jul 9, 2023
0.7.0 Aug 18, 2022
0.2.3 Oct 28, 2020

#159 in Network programming

Download history 873/week @ 2024-01-24 861/week @ 2024-01-31 1020/week @ 2024-02-07 728/week @ 2024-02-14 857/week @ 2024-02-21 1095/week @ 2024-02-28 1280/week @ 2024-03-06 1062/week @ 2024-03-13 1341/week @ 2024-03-20 2104/week @ 2024-03-27 2684/week @ 2024-04-03 2203/week @ 2024-04-10 1421/week @ 2024-04-17 1435/week @ 2024-04-24 1274/week @ 2024-05-01 1058/week @ 2024-05-08

5,608 downloads per month
Used in 5 crates

MIT/Apache

33KB
715 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(false)          // false (default): TUN, true: TAP.
            .packet_info(false)  // false: IFF_NO_PI, default is true.
            .up()                // or set it up manually using `sudo ip link set <tun-name> up`.
            .try_build()         // or `.try_build_mq(queues)` for multi-queue support.
            .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–13MB
~150K SLoC