Sponge
CS144's user-space TCP library
tun.cc
Go to the documentation of this file.
1 #include "tun.hh"
2 
3 #include "util.hh"
4 
5 #include <cstring>
6 #include <fcntl.h>
7 #include <linux/if.h>
8 #include <linux/if_tun.h>
9 #include <sys/ioctl.h>
10 
11 static constexpr const char *CLONEDEV = "/dev/net/tun";
12 
13 using namespace std;
14 
23 
24 TunTapFD::TunTapFD(const string &devname, const bool is_tun)
25  : FileDescriptor(SystemCall("open", open(CLONEDEV, O_RDWR))) {
26  struct ifreq tun_req {};
27 
28  tun_req.ifr_flags = (is_tun ? IFF_TUN : IFF_TAP) | IFF_NO_PI; // tun device with no packetinfo
29 
30  // copy devname to ifr_name, making sure to null terminate
31 
32  strncpy(static_cast<char *>(tun_req.ifr_name), devname.data(), IFNAMSIZ - 1);
33  tun_req.ifr_name[IFNAMSIZ - 1] = '\0';
34 
35  SystemCall("ioctl", ioctl(fd_num(), TUNSETIFF, static_cast<void *>(&tun_req)));
36 }
A reference-counted handle to a file descriptor.
int fd_num() const
underlying descriptor number
TunTapFD(const std::string &devname, const bool is_tun)
Open an existing persistent TUN or TAP device.
Definition: tun.cc:24
T data(T... args)
SystemCall("socketpair", ::socketpair(AF_UNIX, SOCK_STREAM, 0, fds.data()))
T strncpy(T... args)
static constexpr const char * CLONEDEV
Definition: tun.cc:11