1 /*
2  * Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
3  * Use of this source code is governed by a BSD-style license that can be
4  * found in the LICENSE file.
5  */
6 
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 
17 #include <sys/ioctl.h>
18 #include <sys/socket.h>
19 
20 #include <linux/if.h>
21 #include <linux/if_tun.h>
22 
23 static int
tun_alloc(char * dev)24 tun_alloc(char *dev)
25 {
26   struct ifreq ifr;
27   int fd, err;
28 
29   if ((fd = open ("/dev/net/tun", O_RDWR)) < 0) {
30     printf ("Error opening /dev/net/tun: %s\n", strerror (errno));
31     return -1;
32   }
33 
34   memset (&ifr, 0, sizeof (ifr));
35 
36   /* Flags: IFF_TUN   - TUN device (no Ethernet headers)
37    *        IFF_TAP   - TAP device
38    *
39    *        IFF_NO_PI - Do not provide packet information
40    */
41   ifr.ifr_flags = IFF_TAP;
42   if (*dev)
43     strncpy (ifr.ifr_name, dev, IFNAMSIZ);
44 
45   if ((err = ioctl (fd, TUNSETIFF, (void *) &ifr)) < 0) {
46     printf ("Error calling TUNSETIFF: %s\n", strerror (errno));
47     close (fd);
48     return err;
49   }
50   strncpy (dev, ifr.ifr_name, IFNAMSIZ);
51   return fd;
52 }
53 
54 int
main(int argc,const char * argv[])55 main (int argc, const char *argv[])
56 {
57 
58   int fd;
59   char namebuf[IFNAMSIZ];
60 
61   strcpy (namebuf, "pseudo-modem%d");
62   fd = tun_alloc (namebuf);
63   if (fd == -1)
64     exit (1);
65 
66   printf ("%s\n", namebuf);
67   fflush(stdout);
68 
69   while (1)
70     sleep (3600);
71 
72   return 0;
73 }
74