Tun is another Linux virtual network device. It is similar to veTH except that the other end is connected to the kernel protocol stack and the other end is connected to another NetNS protocol stack. One end of the TUN device is connected to the kernel protocol stack, and the other end is connected to a user program. Any data sent from the protocol stack to the TUN network adapter can be read from the user program, and the data written from the user program to /dev/net/TUN will be received by the kernel protocol stack.

When we open the /dev/net/tun device through the program, we will find that there is a network card on our host, open many times will be a new increase in the network card, named tun0/tun1/tun2…. We read and write the Tun card in the same way as we normally read and write a file. The following is an example.

First, write a C program named Tun.c with the following code:

Then compile and execute:

Then open it from another terminal and view the nic:

We found that there was an extra TUN0 nic. We assigned the address to the NIC and started it

Note that when we assign an address to TUN0, there will be an extra route on the host

Finally, ping 192.168.100.101, normally there should be no response, but observe the first terminal opened, found that there is a packet:

If you PING tun0 at 192.168.100.100, you will find a normal ICMP packet response, but terminal 1 does not receive anything. Why PING an address that doesn’t exist? Let’s get this straight:

When ROUTING, it is found that the address of TUN0 is the local address, so it is sent from lo network card. Therefore, tun0 will never receive the packet. To enable Tun0 to receive the packet, you need to ping an address in the same network segment as Tun0. Because this will make the protocol stack to send the packet from TUN0, on the other end is our program, our program did nothing but print the result, so there is no response on the ping side.

For more information please visit: www.deepexi.com/bbs/develop.