5 #include <netinet/in.h>
8 #include <linux/if_tun.h>
10 #include "tunprotocol.h"
16 int tun_open(const char *name) {
19 int fd = open("/dev/net/tun", O_RDWR);
21 perror("/dev/net/tun");
25 memset(&ifr, 0, sizeof(ifr));
26 ifr.ifr_flags = IFF_TUN;
27 strncpy(ifr.ifr_name, name, IFNAMSIZ);
29 int err = ioctl(fd, TUNSETIFF, &ifr);
31 perror("ioctl(TUNSETIFF)");
40 TUNProtocol::TUNProtocol(const char *devname)
41 : tunfd(tun_open(devname)) {
44 void TUNProtocol::send_packet(uint16_t proto, const string &data, int incoming_seq)
50 memcpy(ptr, &flags, sizeof(flags));
54 memcpy(ptr, &proto, sizeof(proto));
57 memcpy(ptr, data.data(), data.size());
59 int len = sizeof(flags) + sizeof(proto) + data.size();
60 if (write(tunfd, buf, len) != len) {
66 int TUNProtocol::fd() const
71 void TUNProtocol::read_packet(Protocol *sender)
74 int ret = read(tunfd, buf, sizeof(buf));
80 fprintf(stderr, "tunfd EOF\n");
85 uint16_t flags = *(uint16_t *)ptr;
87 uint16_t proto = ntohs(*(uint16_t *)ptr);
89 //fprintf(stderr, "tun packet: flags=%x proto=%x len=%d\n",
90 // flags, proto, ret - 4);
91 sender->send_packet(proto, string(ptr, buf + ret), -1);