TUN/TAP provides packet reception and transmission for user space programs. This allow userspace programs to see raw network traffic (at the ethernet or IP level) and do whatever they like with it.

TUN and Tap is on different network level:

  • TUN: L3 IP frames
  • TAP: L2 ethernet frames

further reading: Tun/Tap interface tutorial


TUN/TAP like a virtual L2 or L3 HBA inner OS. 虚拟网卡

1. How to use

To create a tun device named *dev,you can do like this.

#include <linux/if.h>
#include <linux/if_tun.h>

int tun_alloc(char *dev)
struct ifreq ifr;
int fd, err;

if( (fd = open("/dev/net/tun", O_RDWR)) < 0 )
return tun_alloc_old(dev);

memset(&ifr, 0, sizeof(ifr));

/* Flags: IFF_TUN   - TUN device (no Ethernet headers)
*        IFF_TAP   - TAP device
*        IFF_NO_PI - Do not provide packet information
ifr.ifr_flags = IFF_TUN;
if( *dev )
strncpy(ifr.ifr_name, dev, IFNAMSIZ);

if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
return err;
strcpy(dev, ifr.ifr_name);
return fd;

2. commands

  • iproute2
  • tunctl
  • openvpn --mktun

3. vs.

TUN vs. raw sockets

TUN/TAP can be used as a virtual device.

raw sockets is a socket api.

tun/tap vs. veth

TUN/TAP 设备是一种让用户态程序向内核协议栈注入数据的设备,一个工作在三层,一个工作在二层,使用较多的是 TAP 设备。VETH 设备出现较早,它的作用是反转通讯数据的方向,需要发送的数据会被转换成需要收到的数据重新送入内核网络层进行处理,从而间接的完成数据的注入。

4. application




Newer virtualization platforms like libvirt use tap interfaces extensively to communicate with guests that support them like qemu/kvm; the interfaces have usually names like vnet0, vnet1 etc.

Linux tap interfaces created with ip tuntap cannot be used to attach network namespaces to linuxbridges or the openvswitch.

  • https://www.kernel.org/doc/Documentation/networking/tuntap.txt
  • http://en.wikipedia.org/wiki/TUN/TAP
  • http://backreference.org/2010/03/26/tuntap-interface-tutorial/
  • http://www.ibm.com/developerworks/cn/linux/1310_xiawc_networkdevice/