2 #include <netinet/in.h>
9 #include <linux/if_tun.h>
11 #include "tunprotocol.h"
17 int tun_open(const char *name) {
20 int fd = open("/dev/net/tun", O_RDWR);
22 perror("/dev/net/tun");
26 memset(&ifr, 0, sizeof(ifr));
27 ifr.ifr_flags = IFF_TUN;
28 strncpy(ifr.ifr_name, name, IFNAMSIZ);
30 int err = ioctl(fd, TUNSETIFF, &ifr);
32 perror("ioctl(TUNSETIFF)");
41 TUNProtocol::TUNProtocol(const char *devname)
42 : tunfd(tun_open(devname)), seq(0) {
45 void TUNProtocol::send_packet(uint16_t proto, const string &data, int incoming_seq)
51 memcpy(ptr, &flags, sizeof(flags));
55 memcpy(ptr, &proto, sizeof(proto));
58 memcpy(ptr, data.data(), data.size());
60 int len = sizeof(flags) + sizeof(proto) + data.size();
61 if (write(tunfd, buf, len) != len) {
67 int TUNProtocol::fd() const
72 void TUNProtocol::read_packet(Sender *sender)
75 int ret = read(tunfd, buf, sizeof(buf));
81 fprintf(stderr, "tunfd EOF\n");
86 uint16_t flags = *(uint16_t *)ptr;
88 uint16_t proto = ntohs(*(uint16_t *)ptr);
90 //fprintf(stderr, "tun packet: flags=%x proto=%x len=%d\n",
91 // flags, proto, ret - 4);
92 sender->send_packet(proto, string(ptr, buf + ret), seq++);