https://github.com/yaa110/tokio-tun
Asynchronous allocation of TUN/TAP devices in Rust using tokio
https://github.com/yaa110/tokio-tun
async crates rust tap tokio tun
Last synced: 5 months ago
JSON representation
Asynchronous allocation of TUN/TAP devices in Rust using tokio
- Host: GitHub
- URL: https://github.com/yaa110/tokio-tun
- Owner: yaa110
- License: apache-2.0
- Created: 2020-10-03T05:04:24.000Z (about 5 years ago)
- Default Branch: main
- Last Pushed: 2025-02-20T18:24:47.000Z (8 months ago)
- Last Synced: 2025-04-08T13:09:17.720Z (6 months ago)
- Topics: async, crates, rust, tap, tokio, tun
- Language: Rust
- Homepage: https://crates.io/crates/tokio-tun
- Size: 43 KB
- Stars: 88
- Watchers: 2
- Forks: 32
- Open Issues: 10
-
Metadata Files:
- Readme: README.md
- License: LICENSE-APACHE
Awesome Lists containing this project
README
# Tokio TUN/TAP
[](https://github.com/yaa110/tokio-tun/actions) [](https://crates.io/crates/tokio-tun) [](https://docs.rs/tokio-tun) [](examples)
Asynchronous allocation of TUN/TAP devices in Rust using [`tokio`](https://crates.io/crates/tokio). Use [async-tun](https://crates.io/crates/async-tun) for `async-std` version.
## Getting Started
- Create a tun device using `Tun::builder()` and read from it in a loop:
```rust
#[tokio::main]
async fn main() {
let tun = Arc::new(
Tun::builder()
.name("") // if name is empty, then it is set by kernel.
.tap() // uses TAP instead of TUN (default).
.packet_info() // avoids setting IFF_NO_PI.
.up() // or set it up manually using `sudo ip link set up`.
.build()
.unwrap()
.pop()
.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`:
```bash
sudo -E $(which cargo) run
```- Set the address of device (address and netmask could also be set using `TunBuilder`):
```bash
sudo ip a add 10.0.0.1/24 dev
```- Ping to read packets:
```bash
ping 10.0.0.2
```- Display devices and analyze the network traffic:
```bash
ip tuntap
sudo tshark -i
```## Supported Platforms
- [x] Linux
- [ ] FreeBSD
- [ ] Android
- [ ] OSX
- [ ] iOS
- [ ] Windows## Examples
- [`read`](examples/read.rs): Split tun to (reader, writer) pair and read packets from reader.
- [`read-mq`](examples/read-mq.rs): Read from multi-queue tun using `tokio::select!`.```bash
sudo -E $(which cargo) run --example read
sudo -E $(which cargo) run --example read-mq
```