47 lines
1.1 KiB
C++
47 lines
1.1 KiB
C++
#include <linux/if.h>
|
|
#include <linux/if_tun.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/ioctl.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
|
|
#include "TunDevice.hpp"
|
|
|
|
TunDevice::TunDevice(const std::string& dev)
|
|
{
|
|
struct ifreq ifr;
|
|
int fd, err;
|
|
|
|
if( (fd = open("/dev/net/tun", O_RDWR)) < 0 )
|
|
throw TunDevice::InitializationError("Cannot open /dev/net/tun", fd);
|
|
|
|
memset(&ifr, 0, sizeof(ifr));
|
|
|
|
/* Flags: IFF_TUN - TUN device (no Ethernet headers)
|
|
* IFF_TAP - TAP device
|
|
*
|
|
* IFF_NO_PI - Do not provide packet information
|
|
*/
|
|
ifr.ifr_flags = IFF_TUN;
|
|
if(!dev.empty()) {
|
|
if(dev.size() >= IFNAMSIZ - 2)
|
|
throw TunDevice::InitializationError("Device name is too long.");
|
|
strncpy(ifr.ifr_name, dev.c_str(), IFNAMSIZ-1);
|
|
}
|
|
|
|
if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
|
|
close(fd);
|
|
throw TunDevice::InitializationError(
|
|
"Tunnel interface failed [TUNSETIFF]", err
|
|
);
|
|
}
|
|
_dev_name = ifr.ifr_name;
|
|
_fd = fd;
|
|
}
|
|
|
|
TunDevice::~TunDevice() {
|
|
close(_fd);
|
|
}
|