当尝试对TUN设备进行TUNSETIFF时,ioctl返回-1

问题描述

我一直在遵循official文档中创建TUN设备。文档很少,但是似乎没有什么用。这是我到目前为止的内容

\x22

编译步骤为#include <linux/if.h> #include <linux/if_tun.h> #include <sys/fcntl.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> int tun_alloc(char *dev) { struct ifreq ifr; int fd,err; if( (fd = open("/dev/net/tun",O_RDWR)) < 0 ) return 7; // tun_alloc_old(dev); // this does not happen,linux docs don't say what tun_alloc_old is anyway memset(&ifr,sizeof(ifr)); /* Flags: IFF_TUN - TUN device (no Ethernet headers) * IFF_TAP - TAP device * * IFF_NO_PI - Do not provide packet information */ ifr.ifr_flags = IFF_TUN; if( *dev ) { printf("setting ifr.ifr_name to \"%s\"\n",dev); strncpy(ifr.ifr_name,dev,IFNAMSIZ); } printf("ifr.ifr_name is \"%s\"\n",ifr.ifr_name); if( (err = ioctl(fd,TUNSETIFF,(void *) &ifr)) < 0 ){ perror("ERR"); close(fd); printf("GOT ERROR: %d\n",err); return err; } printf("past TUNSETIFF error checking\n"); strcpy(dev,ifr.ifr_name); return fd; } int main() { char name[128]; strcpy(&name,"tun23"); int tun = tun_alloc(name); printf("tun_alloc: %s id: %d\n",name,tun); if(tun == -1) return -1; while(1) { printf("in loop\n"); char buf[128]; ssize_t readamount = read(tun,buf,128); printf("finished read\n"); if(readamount == -1) { printf("read 0 bytes\n"); continue; } printf("Read %d: ",readamount); for(int i = 0; i < 128; i++) { printf("%hhx",buf[i]); } printf("\n"); } return tun; }

以非root用户身份运行时,我得到此输出

gcc -g3 test.c && a.out

作为根用户,它成功进入了循环,但随后对setting ifr.ifr_name to "tun23" ifr.ifr_name is "tun23" ERR: Operation not permitted GOT ERROR: -1 tun_alloc: tun23 id: -1 调用似乎被阻止了。

read

(如果出现XY问题,我这样做的原因是尝试创建一个非常简单的类似vpn的应用程序)

问题在于,尽管它在此循环中受阻,但没有创建TUN设备。我正在寻找setting ifr.ifr_name to "tun23" ifr.ifr_name is "tun23" past TUNSETIFF error checking tun_alloc: tun23 id: 3 in loop 。我不确定如何给它任何字节来读取。

编辑:添加一个正确的/dev/调用和相应的输出perror valgrind输出以及几个打印语句。尝试调试strcpy错误

编辑:修复了strcpy错误,非常简单。似乎由于缺乏创建TUN设备的权限而在非root用户中失败。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)