tun/tap works on incoming or outgoing packet?

The tun/tap interface is the way to pass packets between your application and the kernel network stack.

Create the tap interface:

ip tuntap add dev tun101 mode tun
ip link set up dev tun101
ip a add 192.0.2.1/24 dev tun101

Let's ping some address from subnet assigned to the tun101 interface.

ping 192.0.2.2

What's happen?

  • The ping creates the socket, builds the icmp echo request packet and writes it into the socket.
  • The kernel receives the icmp echo request packets from the ping through the socket, determines the route for this packets and pass the packet into the tuntap driver.
  • For the network stack this packets are local-originated and outgoing into outside.
  • The tuntap driver receives the icmp echo request packets and sends it into your application.
  • Your application calls the read function and gets the icmp echo request packet in the corresponded memory buffer.
  • Your application builds the icmp echo reply packets for received requests.
  • Your application write these replies with the write function.
  • The tuntap driver receives the packets from your application and pass them further into the network stack.
  • For the kernel network stack these packets are incoming form outside.
  • The kernel stack determines these packets as addressed for host itself and sends into the socket, that has been created by the ping.
  • The ping reads the data from socket, calculates the delay and display the received answer.

The read operation in your app means reading the packets, those have been sent into the corresponded tun interface by the kernel network stack. The write operation means sending of packets from your app into the kernel network stack.