gpt4 book ai didi

将 `ip tuntap add` system() 调用转换为 C 代码

转载 作者:太空狗 更新时间:2023-10-29 11:49:02 25 4
gpt4 key购买 nike

我正在尝试将我在 C 中调用 ip tuntap add ...system() 调用转换为不依赖于system() 调用。

基本上,当我的应用程序被强制终止时,我使用 system("ip tuntap add ...") 调用调出的隧道适配器会留在那儿,这是一个问题。

有人告诉我可以使用 rtnetlink实现我的目标。我想将以下行转换为不依赖于 system() 调用的 C 代码。我相信如果我使用 rtnetlink当我的应用程序终止时,我提出的隧道适配器将被内核销毁,这是我想要这样做的主要原因。

这是我在 C 中的当前行:

system("ip tuntap add dev tun1 mode tun");

如果rtnetlink这不是我会如何去做的,当我的应用程序被强行终止时,还有另一种方法会破坏隧道吗?

最佳答案

@ Jonathon Reinhart在评论中回答了这个问题:

您正在寻找的是非持久性 TUN 适配器。而不是使用

system("ip tuntap add dev tun1 mode tun");

函数

Originally taken from simpletun.c, code added to answer to avoid potential issues with dead links in the future.

# 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);

发生了什么事?

调用时,如果新隧道不存在,该函数将创建新隧道并返回隧道的文件描述符。如果它已经存在,它将简单地返回隧道的文件描述符。

当它创建隧道时,如果您的进程终止,它将主动销毁隧道和任何关联的路由。

关于将 `ip tuntap add` system() 调用转换为 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49603416/

25 4 0
文章推荐: linux - uniq -c 不适用于 awk?
文章推荐: asp.net - 水平对齐复选框(表格布局)
文章推荐: html - CSS:没有的垂直列布局