如何检测TUN/TAP设备是否已经存在
我想用代码创建一个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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您向内核询问其中包含
%d
的接口名称,则内核将为您选择一个数字,而您无需执行此操作。请参阅文档,其中包含此注释的示例程序
,在执行
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:
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.