[Network Virtualization] TUN/TAP
Contents
The TUN/TAP virtual network device is connected to the protocol stack at one end, and at the other end is not a physical network, but another application in user space. That is, the packets sent from the protocol stack to the TUN/TAP can be read by the application, and of course the application can send packets directly to the TUN/TAP.
A typical TUN/TAP example is shown in the following figure.
In the above figure we have configured a physical NIC with IP 18.12.0.92
and tun0 is a TUN/TAP device with IP 10.0.0.12
. The packets flow in the following directions.
- application A sends a packet through socket A. Assume that the destination IP address of this packet is
10.0.0.22
. - socket A drops the packet to the protocol stack.
- the protocol stack sends the packet to the tun0 device according to the local routing rules and the destination IP of the packet
- tun0 receives the packet and forwards it to application B in user space
- application B receives the packet and constructs a new packet, embedding the original packet in the new packet (IPIP packet), and finally forwards the packet through socket B.
Note: The source address of the new packet becomes the eth0 address, while the destination IP address becomes another address 18.13.0.91.
- socket B sends the packet to the protocol stack
- The protocol stack decides that this packet is to be sent out through eth0 based on the local routing rules and the destination IP of the packet, and forwards the packet to eth0.
- eth0 sends the packet out over the physical network.
We see that the network packet sent to 10.0.0.22
is sent to 18.13.0.91
on the remote network via application B in user space using 18.12.0.92
, and the network packet arrives at 18.13.0.91
, reads the original packet inside, reads the original packet inside, and forwards it to the local 10.0.0.22
. This is the basic principle of VPN.
Using TUN/TAP devices we have the opportunity to forward some of the packets in the protocol stack to the application in user space and let the application process the packets. Common usage scenarios include data compression, encryption and other functions.
Note: The difference between TUN and TAP devices is that TUN device is a virtual end-to-end IP layer device, which means that user-space applications can only read and write IP network packets (layer 3) through TUN device, while TAP device is a virtual link layer device, which can read and write link layer packets (layer 2) through TAP device. Use
-dev tun
and-dev tap
to differentiate when creating devices with the-ip
command.
Code example
Here a program is written, it receives the packet from tun device, only print out how many bytes of packet received, nothing else is done, how to program please refer to the reference link at the back.
|
|
Virtual Device Demo
|
|
Reference
Reference https://houmin.cc/posts/c892b507/