Skip to content

Instantly share code, notes, and snippets.

@wxdao
Forked from bringhurst/gist:1693075
Last active April 13, 2024 18:39
Show Gist options
  • Save wxdao/8a0c83ed6cb2a141d1176499e3f6fc48 to your computer and use it in GitHub Desktop.
Save wxdao/8a0c83ed6cb2a141d1176499e3f6fc48 to your computer and use it in GitHub Desktop.
How to open utun device in OS X
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/kern_control.h>
#include <net/if_utun.h>
#include <sys/ioctl.h>
#include <sys/kern_event.h>
int open_utun(int num) {
int err;
int fd;
struct sockaddr_ctl addr;
struct ctl_info info;
fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
if (fd < 0) {
return fd;
}
memset(&info, 0, sizeof (info));
strncpy(info.ctl_name, UTUN_CONTROL_NAME, strlen(UTUN_CONTROL_NAME));
err = ioctl(fd, CTLIOCGINFO, &info);
if (err < 0) {
close(fd);
return err;
}
addr.sc_id = info.ctl_id;
addr.sc_len = sizeof(addr);
addr.sc_family = AF_SYSTEM;
addr.ss_sysaddr = AF_SYS_CONTROL;
addr.sc_unit = num + 1; // utunX where X is sc.sc_unit -1
err = connect(fd, (struct sockaddr*)&addr, sizeof(addr));
if (err < 0) {
// this utun is in use
close(fd);
return err;
}
return fd;
}
int main(void) {
int fd;
for (int num = 0; num < 255; ++num) {
fd = open_utun();
if (fd >= 0) {
break;
}
}
// hava fun
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment