我正在尝试将C中调用ip tuntap add ...的ip tuntap add ...调用转换为不依赖于system()调用的C代码。
基本上,当我的应用程序被强制终止时,我使用system("ip tuntap add ...")调用的隧道适配器留在那里是一个问题。
有人告诉我,我可以用rtnetlink来实现我的目标。我想将下面的行转换为不依赖system()调用的C代码。我相信,如果我使用rtnetlink,当我的应用程序终止时,我打开的隧道适配器将被内核销毁,这也是我想要这样做的主要原因。
这是我现在的C行:
system("ip tuntap add dev tun1 mode tun");如果rtnetlink不是我要这么做的方式,那么当我的应用程序被强制终止时,还有另一种方法会破坏隧道吗?
发布于 2018-04-02 18:33:18
@乔纳森·莱因哈特在评论中回答了这一点:
您要寻找的是一个非持久的TUN适配器。而不是使用
system("ip tuntap add dev tun1 mode tun");功能
最初是从simpletun.c中提取的,添加代码是为了避免将来出现死链接的潜在问题。
# Not certain that these are all of the imports you'll need,
# but i'm pretty sure it covers everything.
#include <net/if.h>
#include <linux/if_tun.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <string.h>
#include <stdio.h>
int tun_alloc(char *dev, int flags) {
struct ifreq ifr;
int fd, err;
char *clonedev = "/dev/net/tun";
if( (fd = open(clonedev , O_RDWR)) < 0 ) {
perror("Opening /dev/net/tun");
return fd;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = flags;
if (*dev) {
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
}
if( (err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0 ) {
perror("ioctl(TUNSETIFF)");
close(fd);
return err;
}
strcpy(dev, ifr.ifr_name);
return fd;
}叫它
int tun_fd = tun_alloc("tun1", IFF_TUN | IFF_NO_PI);发生什么事了呢?
当它被调用时,如果它不存在,这个函数将创建新的隧道,并返回隧道的文件描述符。如果它已经存在,它将只返回隧道的文件描述符。
当它创建隧道时,如果您的进程死亡,它将主动破坏隧道和任何相关的路由。
https://stackoverflow.com/questions/49603416
复制相似问题