gpt4 book ai didi

macos - 如何在 macOS 中创建虚拟界面?

转载 作者:行者123 更新时间:2023-12-02 16:57:09 24 4
gpt4 key购买 nike

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

我发现一些实现此功能的软件创建了utun2接口(interface),我不知道该怎么做。有什么好的例子吗?

最佳答案

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

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);
}

关于macos - 如何在 macOS 中创建虚拟界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56003563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com