current stuff, untested
[netsniff-ng.git] / src / tundev.c
blob9e143c8e7381a47a8472d0a981a46da66ff7b9ba
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Portions of this code derived and modified from:
4 * Copyright 1998-2000 Maxim Krasnyansky <max_mk@yahoo.com>
5 * VTun has been derived from VPPP package by Maxim Krasnyansky.
6 * Subject to the GPL, version 2.
7 * By Daniel Borkmann <daniel@netsniff-ng.org>
8 * Copyright 2011 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
9 * Swiss federal institute of technology (ETH Zurich)
10 * Subject to the GPL.
13 #include <fcntl.h>
14 #include <unistd.h>
15 #include <sys/ioctl.h>
16 #include <sys/socket.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <linux/if.h>
20 #include <linux/if_tun.h>
22 #include "tundev.h"
23 #include "die.h"
25 static int __tun_open_or_die(void)
27 int i, fd;
28 char tunname[IFNAMSIZ];
30 for (i = 0; i < 255; ++i) {
31 memset(tunname, 0, sizeof(tunname));
32 sprintf(tunname, "/dev/tun%d", i);
34 fd = open(tunname, O_RDWR);
35 if (fd > 0)
36 return fd;
39 panic("Cannot open tunnel device!\n");
40 return 0; /* never reached, but to suppress compiler warning */
43 #ifndef OTUNSETIFF
44 # define OTUNSETIFF (('T' << 8) | 202)
45 #endif
47 int tun_open_or_die(void)
49 int fd, ret;
50 struct ifreq ifr;
52 fd = open("/dev/net/tun", O_RDWR);
53 if (fd < 0)
54 return __tun_open_or_die();
56 memset(&ifr, 0, sizeof(ifr));
57 ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
59 ret = ioctl(fd, TUNSETIFF, &ifr);
60 if (ret < 0) {
61 if (errno == EBADFD) {
62 ret = ioctl(fd, OTUNSETIFF, &ifr);
63 if (ret < 0)
64 panic("ioctl screwed up 1!\n");
65 } else
66 panic("ioctl screwed up 2!\n");
69 return fd;
72 ssize_t tun_write(int fd, const void *buf, size_t count)
74 return write(fd, buf, count);
77 ssize_t tun_read(int fd, void *buf, size_t count)
79 return read(fd, buf, count);
82 void tun_close(int fd)
84 close(fd);