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;
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. .try_build() .await?;
println!("tun created, name: {}, fd: {}", tun.name(), tun.as_raw_fd());
loop {
let mut buf = [0u8; 1024];
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 link set dev <tun-name> up
➜ sudo ip a add 10.0.0.1/24 dev <tun-name>
bash
➜ ping 10.0.0.2
➜ sudo tshark -i <tun-name>