A simple way to open a TUN interface
- Rust 100%
| .forgejo/workflows | ||
| examples | ||
| src | ||
| .gitignore | ||
| Cargo.toml | ||
| LICENSE | ||
| README.md | ||
easy-tun
easy-tun is a pure-Rust library that can bring up and manage a TUN interface by directly interacting with the Universal TUN/TAP Driver.
Requirements
- Linux (glibc or musl)
- Root privileges or
CAP_NET_ADMINcapability
Installation
Add easy-tun to your Cargo.toml:
[dependencies]
easy-tun = "2"
Usage
Single queue
use std::io::Read;
use easy_tun::Tun;
fn main() -> std::io::Result<()> {
let tun = Tun::new("tun%d", 1)?;
println!("Created device: {}", tun.name());
let mut buffer = [0u8; 1500];
let n = tun.fd(0).unwrap().read(&mut buffer)?;
println!("Read {} bytes", n);
Ok(())
}
Multi-queue
use std::{io::Read, sync::Arc};
use easy_tun::Tun;
fn main() -> std::io::Result<()> {
let tun = Arc::new(Tun::new("tun%d", 5)?);
println!("Created device: {}", tun.name());
let mut handles = Vec::new();
for i in 0..tun.queue_count() {
let tun = Arc::clone(&tun);
handles.push(std::thread::spawn(move || {
let mut buffer = [0u8; 1500];
loop {
let n = tun.fd(i).unwrap().read(&mut buffer).unwrap();
println!("Queue {}: read {} bytes", i, n);
}
}));
}
for h in handles {
h.join().unwrap();
}
Ok(())
}
Platform Support
This crate currently supports Linux with glibc or musl. Other platforms are not supported.