modified: nfig1.py
[GalaxyCodeBases.git] / etc / Mac / utun / 17-15-utun.c
blobee09cba2bc8cb4c5fe8429fe41261fad3966c3c6
1 #include <sys/types.h>
2 #include <sys/ioctl.h>
3 #include <sys/socket.h>
4 #include <sys/sys_domain.h>
5 #include <sys/kern_control.h>
6 #include <net/if_utun.h>
7 #include <errno.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <syslog.h>
11 #include <unistd.h>
13 #include <stdlib.h> // exit, etc.
16 // Simple User-Tunneling Proof of Concept - extends listing 17-15 in book
17 //
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
25 int
26 tun(void)
28 struct sockaddr_ctl sc;
29 struct ctl_info ctlInfo;
30 int fd;
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");
37 return -1;
39 fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
41 if (fd == -1) {
42 perror ("socket(SYSPROTO_CONTROL)");
43 return -1;
45 if (ioctl(fd, CTLIOCGINFO, &ctlInfo) == -1) {
46 perror ("ioctl(CTLIOCGINFO)");
47 close(fd);
48 return -1;
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)");
63 close(fd);
64 return -1;
66 return fd;
69 int
70 main (int argc, char **argv)
72 int utunfd = tun();
74 if (utunfd == -1)
76 fprintf(stderr,"Unable to establish UTUN descriptor - aborting\n");
77 exit(1);
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...
86 for (;;)
88 unsigned char c[1500];
89 int len;
90 int i;
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");
101 printf ("\n");
106 return(0);