How to utilize TUN/TAP tunnel from user program

networkingtunneling

I recently discovered the existence of Linux TUN/TAP interfaces and am still trying to understand them. I think I get the basic concept – pseudo devices are created which emulate a network interface and instead of passing data to hardware it is passed to a userspace program.

How would you direct an unrelated program to utilize this tunnel?

For example, before the tunnel is created my system only contains eth0 and lo, the normal ethernet interface (wired to my local network) and the loopback interface. After a program creates and configures a tunnel, I have a new interface gr0 which I gave an IP address that is on my local network, but not in use (so we are all on the same subnet). How would I make an unrelated program utilize this 'tunnel'? Say I had a simple Python message passing client/server app which utilizes a TCP connection, how could I configure it to use the tunnel?

I apologize if I am missing something basic, but as usual I have managed to confuse myself in the scheme of things. Again, all I want is to have a simple TCP program utilize this tunnel.

Thanks!

Best Answer

It's not always "tunnel". TUN/TAP is just specific NIC drivers. From point of view of network stack they acts as any other network interfaces: they can have IP addresses, can be point-to-point or broadcast interfaces. Routing rules also applies to them. But all traffic that gets written to one of that network interfaces goes to some userspace program for processing, and all data written by userspace program directly to /dev/tunX looks like incoming packets for network stack.

In usual tunneling setup server and client have TUN devices with assigned addresses. Routing tables configured on both of them directs needed traffic to this TUN devices. When packet get routed to tun0, kernel sends it to userspace program (client) that sends this packet to other program on remote machine (server) via, for example, TCP connection. On remote machine other program (server) recieves packet from client and writes it to it's own /dev/tunX device, "injecting" that packet into network stack. And tunneled packet gets processed as any other.

Related Question