48inline int utun_open(std::string &name,
const int unit)
50 struct sockaddr_ctl sc;
51 struct ctl_info ctlInfo;
53 memset(&ctlInfo, 0,
sizeof(ctlInfo));
54 if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME,
sizeof(ctlInfo.ctl_name))
55 >=
sizeof(ctlInfo.ctl_name))
56 throw utun_error(
"UTUN_CONTROL_NAME too long");
58 ScopedFD fd(socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL));
60 throw utun_error(
"socket(SYSPROTO_CONTROL)");
62 if (ioctl(fd(), CTLIOCGINFO, &ctlInfo) == -1)
63 throw utun_error(
"ioctl(CTLIOCGINFO)");
65 sc.sc_id = ctlInfo.ctl_id;
66 sc.sc_len =
sizeof(sc);
67 sc.sc_family = AF_SYSTEM;
68 sc.ss_sysaddr = AF_SYS_CONTROL;
69 sc.sc_unit = unit + 1;
70 std::memset(sc.sc_reserved, 0,
sizeof(sc.sc_reserved));
74 if (connect(fd(), (
struct sockaddr *)&sc,
sizeof(sc)) == -1)
79 socklen_t utunname_len =
sizeof(utunname);
80 if (getsockopt(fd(), SYSPROTO_CONTROL, UTUN_OPT_IFNAME, utunname, &utunname_len))
81 throw utun_error(
"getsockopt(SYSPROTO_CONTROL)");