#tun #tap #async #tokio

tokio-tun

Asynchronous allocation of TUN/TAP devices using tokio

24 releases

Uses new Rust 2021

new 0.5.1 Jan 13, 2022
0.5.0 Dec 7, 2021
0.4.0 Oct 27, 2021
0.3.14 Jul 3, 2021
0.2.3 Oct 28, 2020

#77 in Asynchronous

Download history 2/week @ 2021-09-26 31/week @ 2021-10-03 38/week @ 2021-10-10 5/week @ 2021-10-17 27/week @ 2021-10-24 8/week @ 2021-10-31 25/week @ 2021-11-07 7/week @ 2021-11-14 10/week @ 2021-11-21 7/week @ 2021-11-28 65/week @ 2021-12-05 11/week @ 2021-12-12 10/week @ 2021-12-19 13/week @ 2021-12-26 66/week @ 2022-01-02 33/week @ 2022-01-09

122 downloads per month
Used in 3 crates

MIT/Apache

29KB
643 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 TunBuilder and read from it in a loop:
#[tokio::main]
async fn main() -> Result<()> {
    let tun = TunBuilder::new()
        .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.

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

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

    let mut buf = [0u8; 1024];
    loop {
        let n = reader.read(&mut buf).await?;
        println!("reading {} bytes: {:?}", n, &buf[..n]);
    }
}
  • Run the code using sudo:
  sudo -E /path/to/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!.

Dependencies

~4.5MB
~78K SLoC