如何检测 tun/tap 设备是否已经存在

How to detect if a tun/tap device already exists

我想用代码创建一个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;
    }

如果你向内核询问一个带有%d的接口名称,内核会为你选择一个数字,你不需要这样做。

请参阅 documentation,其中包含带有以下注释的示例程序:

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")

如评论所述,在执行TUNSETIFF 以格式字符串设置接口名称后,缓冲区将被内核选择的名称覆盖。确保它足够大 - IFNAMSIZ 字节,包括空终止符。