13 releases

new 0.5.1 Feb 23, 2021
0.5.0 Apr 4, 2020
0.4.4 May 4, 2019
0.4.2 Jan 8, 2018
0.3.0 Jun 2, 2017

#51 in Network programming

Download history 435/week @ 2020-11-04 416/week @ 2020-11-11 695/week @ 2020-11-18 580/week @ 2020-11-25 548/week @ 2020-12-02 716/week @ 2020-12-09 326/week @ 2020-12-16 287/week @ 2020-12-23 353/week @ 2020-12-30 655/week @ 2021-01-06 531/week @ 2021-01-13 696/week @ 2021-01-20 488/week @ 2021-01-27 649/week @ 2021-02-03 2219/week @ 2021-02-10 951/week @ 2021-02-17

2,953 downloads per month

WTFPL license

77KB
2K SLoC

TUN interfaces Crates.io tun WTFPL

This crate allows the creation and usage of TUN interfaces, the aim is to make this cross-platform.

Usage

First, add the following to your Cargo.toml:

[dependencies]
tun = "0.3"

Next, add this to your crate root:

extern crate tun;

If you want to use the TUN interface with mio/tokio, you need to enable the mio feature:

[dependencies]
tun = { version = "0.3", features = ["mio"] }

Example

The following example creates and configures a TUN interface and starts reading packets from it.

use std::io::Read;

extern crate tun;

fn main() {
	let mut config = tun::Configuration::default();
	config.address((10, 0, 0, 1))
	       .netmask((255, 255, 255, 0))
	       .up();

	#[cfg(target_os = "linux")]
	config.platform(|config| {
		config.packet_information(true);
	});

	let mut dev = tun::create(&config).unwrap();
	let mut buf = [0; 4096];

	loop {
		let amount = dev.read(&mut buf).unwrap();
		println!("{:?}", &buf[0 .. amount]);
	}
}

Platforms

Not every platform is supported.

Linux

You will need the tun module to be loaded and root is required to create interfaces.

macOS

It just werks, but you have to set up routing manually.

iOS

You can pass the file descriptor of the TUN device to rust-tun to create the interface.

Here is an example to create the TUN device on iOS and pass the fd to rust-tun:

// Swift
class PacketTunnelProvider: NEPacketTunnelProvider {
    override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
        let tunnelNetworkSettings = createTunnelSettings() // Configure TUN address, DNS, mtu, routing...
        setTunnelNetworkSettings(tunnelNetworkSettings) { [weak self] error in
            let tunFd = self?.packetFlow.value(forKeyPath: "socket.fileDescriptor") as! Int32
            DispatchQueue.global(qos: .default).async {
                start_tun(tunFd)
            }
            completionHandler(nil)
        }
    }
}
#[no_mangle]
pub extern "C" fn start_tun(fd: std::os::raw::c_int) {
    let mut rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut cfg = tun::Configuration::default();
        cfg.raw_fd(fd);
        let mut tun = tun::create_as_async(&cfg).unwrap();
        let mut framed = tun.into_framed();
        while let Some(packet) = framed.next().await {
            ...
        }
    });
}

Dependencies

~0.4–1.5MB
~32K SLoC