如何检测TUN/TAP设备是否已经存在

发布于 2025-01-23 02:18:35 字数 419 浏览 0 评论 0原文

我想用代码创建一个TUN设备,因此在创建它之前,我想检查一下TUN设备是否已经存在,

现在我正在确定文件是否已经存在,但是此方法不优雅

,更好方式

    char tun_dev_name[IFNAMSIZ + 15];
    for(int tun_num = 0; ;tun_num++)
    {
        sprintf(ifr.ifr_name, "tun%d", tun_num);
        //TODO it is not graceful
        sprintf(tun_dev_name, "/sys/class/net/%s", ifr.ifr_name);
        if(access(tun_dev_name, F_OK) != 0 )
            break;
    }

I want to create a tun device with the code, so before creating it I want to check if the tun device already exists

Right now I'm doing this by determining if the file already exists, but this method is not graceful

Is there a better way

    char tun_dev_name[IFNAMSIZ + 15];
    for(int tun_num = 0; ;tun_num++)
    {
        sprintf(ifr.ifr_name, "tun%d", tun_num);
        //TODO it is not graceful
        sprintf(tun_dev_name, "/sys/class/net/%s", ifr.ifr_name);
        if(access(tun_dev_name, F_OK) != 0 )
            break;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巷子口的你 2025-01-30 02:18:35

如果您向内核询问其中包含%d的接口名称,则内核将为您选择一个数字,而您无需执行此操作。

请参阅文档,其中包含此注释的示例程序

char *dev应该是具有格式字符串(例如“ tun%d”)的设备的名称,但是(据我所知)这可以是任何有效的网络设备名称。
请注意,字符指针被真实设备名称(例如“ TUN0”)覆盖

,在执行tunsetiff以用格式字符串设置接口名称后,缓冲区被覆盖命名选定的内核。确保它足够大 - ifnamsiz字节(包括null终结者)。

If you ask the kernel for an interface name with a %d in it, the kernel will choose a number for you and you won't need to do this.

See documentation which includes an example program with this comment:

char *dev should be the name of the device with a format string (e.g. "tun%d"), but (as far as I can see) this can be any valid network device name.
Note that the character pointer becomes overwritten with the real device name (e.g. "tun0")

As the comment says, after you execute TUNSETIFF to set the interface name with a format string, the buffer is overwritten with the name the kernel selected. Make sure it's large enough - IFNAMSIZ bytes including null terminator.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文