3 #include <sys/socket.h>
4 #include <sys/sys_domain.h>
5 #include <sys/kern_control.h>
6 #include <net/if_utun.h>
13 #include <stdlib.h> // exit, etc.
16 // Simple User-Tunneling Proof of Concept - extends listing 17-15 in book
18 // Compiles for both iOS and OS X..
20 // Coded by Jonathan Levin. Go ahead; Copy, improve - all rights allowed.
22 // (though credit where credit is due would be nice ;-)
23 // http://www.newosxbook.com/src.jl?tree=listings&file=17-15-utun.c http://www.newosxbook.com/index.php?page=code
28 struct sockaddr_ctl sc
;
29 struct ctl_info ctlInfo
;
33 memset(&ctlInfo
, 0, sizeof(ctlInfo
));
34 if (strlcpy(ctlInfo
.ctl_name
, UTUN_CONTROL_NAME
, sizeof(ctlInfo
.ctl_name
)) >=
35 sizeof(ctlInfo
.ctl_name
)) {
36 fprintf(stderr
,"UTUN_CONTROL_NAME too long");
39 fd
= socket(PF_SYSTEM
, SOCK_DGRAM
, SYSPROTO_CONTROL
);
42 perror ("socket(SYSPROTO_CONTROL)");
45 if (ioctl(fd
, CTLIOCGINFO
, &ctlInfo
) == -1) {
46 perror ("ioctl(CTLIOCGINFO)");
51 sc
.sc_id
= ctlInfo
.ctl_id
;
52 sc
.sc_len
= sizeof(sc
);
53 sc
.sc_family
= AF_SYSTEM
;
54 sc
.ss_sysaddr
= AF_SYS_CONTROL
;
55 sc
.sc_unit
= 2; /* Only have one, in this example... */
58 // If the connect is successful, a tun%d device will be created, where "%d"
59 // is our unit number -1
61 if (connect(fd
, (struct sockaddr
*)&sc
, sizeof(sc
)) == -1) {
62 perror ("connect(AF_SYS_CONTROL)");
70 main (int argc
, char **argv
)
76 fprintf(stderr
,"Unable to establish UTUN descriptor - aborting\n");
80 fprintf(stderr
,"Utun interface is up.. Configure IPv4 using \"ifconfig utun1 _ipA_ _ipB_\"\n");
81 fprintf(stderr
," Configure IPv6 using \"ifconfig utun1 inet6 _ip6_\"\n");
82 fprintf(stderr
,"Then (e.g.) ping _ipB_ (IPv6 will automatically generate ND messages)\n");
85 // PoC - Just dump the packets...
88 unsigned char c
[1500];
93 len
= read (utunfd
,c
, 1500);
95 // First 4 bytes of read data are the AF: 2 for AF_INET, 1E for AF_INET6, etc..
96 for (i
= 4; i
< len
; i
++)
98 printf ("%02x ", c
[i
]);
99 if ( (i
-4)%16 ==15) printf("\n");