Asynchronous allocation of TUN/TAP devices in Rust using tokio
. Use async-tun for async-std
version.
TunBuilder
and read from it in a loop:```rust
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.
.packetinfo(false) // false: IFFNOPI, default is true.
.up() // or set it up manually using sudo ip link set <tun-name> up
.
.trybuild()?; // 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]);
}
} ```
sudo
:bash
➜ sudo -E /path/to/cargo run
TunBuilder
):bash
➜ sudo ip a add 10.0.0.1/24 dev <tun-name>
bash
➜ ping 10.0.0.2
➜ ip tuntap
➜ sudo tshark -i <tun-name>