如何在Windows C程序中使用tun设备

时间:2014-02-20 02:07:00

标签: c linux windows networking tun

之前我在Linux上使用过tun设备,需要在Windows上移植我的代码。我在Windows上安装了来自OpenVPN的tun / tap驱动程序,但我无法弄清楚如何在Windows C程序中为该tun设备创建设备句柄。

基本上我需要帮助创建tun设备并获取句柄。

我在Linux上使用的代码如下(类似于kernel.org上的示例)

int mktun (char * dev, int flags, struct ifreq * ifr) {

    int fd, stat;
    char * clonedev = "/dev/net/tun";


    /* Get the file descriptor from the tun clone to use as input to ioctl() */
    if ( (fd = open(clonedev, O_RDWR) ) < 0 )
        return fd;

    /* Now prepare the structure ifreq for ioctl() */
    memset(ifr, 0, sizeof(*ifr));                   /* reset memory to 0 */
    ifr->ifr_flags = flags;             /* set the flags IFF_TUN or IFF_TAP and IFF_NO_PI */

    if (*dev)
        strcpy(ifr->ifr_name, dev);

    /* Now we try and create a device */
    if ( (stat = ioctl(fd, TUNSETIFF, (void *) ifr) ) < 0 ) {
        perror("ioctl()");
        close(fd);
        return stat;
    }

    /* Now write back the name of the interface to dev just to be sure */
    strcpy(dev, ifr->ifr_name);

    /* Now return the file descriptor that can be used to talk to the tun interface */
    return fd;
}

0 个答案:

没有答案