Linux TUN/TAP

Last update: 2024-12-30 08:13:57 +0800 +0800
Available translations: 日本語 / 中文(简体) / 中文(繁體)

TUN/TAP creates virtual network interfaces connected to a userspace file descriptor. A TUN device carries layer-3 IP packets; a TAP device carries layer-2 Ethernet frames. They are used by VPNs, packet analyzers, userspace network stacks, and virtual machines.

Creating an Interface #

Open /dev/net/tun read-write and issue TUNSETIFF with an ifreq. Set IFF_TUN or IFF_TAP; add IFF_NO_PI when the program should receive only packets or frames. Without IFF_NO_PI, each read starts with a four-byte packet-information header containing flags and protocol. The kernel creates the network interface, after which ip link, ip address, and ip route configure its administrative state, addresses, and routes.

On systems that do not create it automatically, the device node is character device major 10, minor 200. Access must be controlled carefully: creating an interface or attaching it to a network namespace requires suitable privileges. Closing the final file descriptor removes a non-persistent TUN/TAP interface unless it was configured with persistence.

Packet Direction #

Packets written by the program are received by the kernel as if they arrived on the virtual interface. Packets the kernel transmits through that interface are returned by read(2) to the program. ip tuntap add dev tun0 mode tun or mode tap performs the basic creation without a custom C program.

Comments

Read or comment on GitHub (sign-in required to comment)