【问题标题】:How to create virtual interface in macOS?如何在 macOS 中创建虚拟界面?
【发布时间】:2019-09-23 23:49:39
【问题描述】:

我想为无法设置 VPN 的设备编写一个简单的 VPN。在 Linux 中我可以创建一个 tun 接口来处理这个问题。但在 macOS 中,我在/dev/ 中找不到任何 tun 接口。

我找了一些实现这个功能的软件创建了utun2接口,不知道怎么做。有什么好的例子吗?

【问题讨论】:

    标签: macos vpn


    【解决方案1】:

    我找到了关于这个问题的两个很好的链接。

    OpenVPNA node packe

    下面是如何在 macOS 中创建 uTun 接口:

    #include <uv.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/kern_event.h>
    #include <sys/socket.h>
    #include <strings.h>
    #include <sys/ioctl.h>
    #include <sys/kern_control.h>
    #include <ctype.h>
    #include <fcntl.h>
    
    
    #define UTUN_CONTROL_NAME "com.apple.net.utun_control"
    #define UTUN_OPT_IFNAME 2
    
    int open_tun_socket () {
      struct sockaddr_ctl addr;
      struct ctl_info info;
      char ifname[20];
      socklen_t ifname_len = sizeof(ifname);
      int fd = -1;
      int err = 0;
    
      fd = socket (PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
      if (fd < 0) return fd;
    
      bzero(&info, sizeof (info));
      strncpy(info.ctl_name, UTUN_CONTROL_NAME, MAX_KCTL_NAME);
    
      err = ioctl(fd, CTLIOCGINFO, &info);
      if (err != 0) goto on_error;
    
      addr.sc_len = sizeof(addr);
      addr.sc_family = AF_SYSTEM;
      addr.ss_sysaddr = AF_SYS_CONTROL;
      addr.sc_id = info.ctl_id;
      addr.sc_unit = 0;
    
      err = connect(fd, (struct sockaddr *)&addr, sizeof (addr));
      if (err != 0) goto on_error;
    
      // TODO: forward ifname (we just expect it to be utun0 for now...)
      err = getsockopt(fd, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, ifname, &ifname_len);
      if (err != 0) goto on_error;
    
      printf("%s",ifname);
    
      // There is to close the socket,But in this case I don't need it.
      //err = fcntl(fd, F_SETFL, O_NONBLOCK);
      //if (err != 0) goto on_error;
    
      //fcntl(fd, F_SETFD, FD_CLOEXEC);
      //if (err != 0) goto on_error;
    
    on_error:
      if (err != 0) {
        close(fd);
        return err;
      }
    
      return fd;
    }
    
    int main(){
        int result = open_tun_socket();
        while( true ){
        }
        printf("%d",result);
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-19
      • 2018-03-23
      • 2021-07-10
      • 2015-03-09
      • 2017-10-23
      • 2020-07-13
      • 2011-04-09
      • 2016-05-17
      相关资源
      最近更新 更多