Asynchronous allocation of TUN/TAP devices in Rust using async-std
.
TunBuilder
and read from it in a loop:```rust use asyncstd::os::unix::io::AsRawFd; use asyncstd::prelude::*; use asyncstd::task; use asynctun::result::Result; use async_tun::TunBuilder; use std::net::Ipv4Addr;
async fn asyncmain() -> Result<()> {
let mut 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
.
.try_build()
.await?;
println!("tun created, name: {}, fd: {}", tun.name(), tun.as_raw_fd());
let mut buf = [0u8; 1024];
loop {
let n = tun.read(&mut buf).await?;
println!("reading {} bytes: {:?}", n, &buf[..n]);
}
}
fn main() -> Result<()> { task::blockon(asyncmain()) } ```
sudo
:bash
➜ sudo -E /path/to/cargo run
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>