Raw socket vs TUN device

3.1k views Asked by At

What is the difference between sending IP packets (from user-space) to a tun device and using a raw socket?

For the purpose of tunneling IP packets through user-space. Why would I use one method over the other?

raw socket:

s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
send(s, ip_pkt, len, 0);

tun device:

struct ifreq ifr;
fd = open("/dev/net/tun", O_RDWR);
ifr.ifr_flags = IFF_TUN;
ioctl(fd, TUNSETIFF, (void *) &ifr)
send(s, ip_pkt, len, 0);
1

There are 1 answers

0
Stian Skjelstad On

A TUN or a TAP device (just differeny layers in the OSI model), are actual virtual network cards that appear in all of the different tools like iptables, ifconfig, ip, route, tcpdump. So packets you write to this socket appear as they arrived remotely on the wire of this virtual network card.

SOCK_RAW method inserts the packet into the IP-stack, and it will appear as it it sent from a user-space application and should be output to a network card according to the routing table and/or flags configuring on the socket.