创建 tun 设备时出错(参数无效)

Error creating tun device (Invalid argument)

我在这里引用示例:https://www.kernel.org/doc/Documentation/networking/tuntap.txt (which is quite old), but the link here suggests that the same thing should work as well: (http://backreference.org/2010/03/26/tuntap-interface-tutorial/)。 否则,我几乎找不到最新的文档。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>  
#include <sys/ioctl.h>
#include <sys/socket.h> 
#include <linux/if.h>
#include <linux/if_tun.h>

int main(void) {
    char *clonedev = "/dev/net/tun"; 
    int fd, err;
    char * dev_name = "tun0";
    struct ifreq ifr;
   if( (fd = open(clonedev, O_RDWR)) < 0 ) {
        exit(1);
   }
   memset(&ifr, 0, sizeof(ifr));
   strncpy(ifr.ifr_name, dev_name, IFNAMSIZ);

   printf("Opened %s \n", ifr.ifr_name);
    if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) {
        printf("Failed to creat tun device (errno is %d)\n",
             errno);
        perror("ioctl");
        close(fd);
        exit(1);
   }
   printf("device created");
}

输出:

Opened tun0 
Failed to creat tun device (errno is 22)
ioctl: Invalid argument

编辑:Grepping OpenVPN 源代码显示相同的用法:

src/openvpn/tun.c:1681:      if (ioctl (tt->fd, TUNSETIFF, (void *) &ifr) < 0)

你没有这样的东西,你的两个链接都有:

ifr.ifr_flags = IFF_TUN; 

似乎是获得无效参数错误的一种非常合理的方法。

你错过了示例中的这一行

ifr.ifr_flags = flags;   /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */

所以,在 ioctl() 之前缺少这个

ifr.ifr_flags = IFF_TUN; 

ifr.ifr_flags = IFF_TAP;