#include <assert.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <linux/if_tun.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>

#define CLEAR(x) memset(&(x), 0x00, sizeof(x))

#define IFNAME "tap0"

#define BUFLEN 1600

static int tun_alloc(char *dev)
{
    struct ifreq ifr;
    int fd, err;

    if( (fd = open("/dev/net/tun", O_RDWR)) < 0 ) {
        perror("Cannot open TUN/TAP dev\n"
                    "Make sure one exists with "
                    "'$ mknod /dev/net/tun c 10 200'");
        exit(1);
    }

    CLEAR(ifr);

    /* Flags: IFF_TUN   - TUN device (no Ethernet headers)
     *        IFF_TAP   - TAP device
     *
     *        IFF_NO_PI - Do not provide packet information
     */
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
    if( *dev ) {
        strncpy(ifr.ifr_name, dev, IFNAMSIZ);
    }

    if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
        perror("ERR: Could not ioctl tun");
        close(fd);
        return err;
    }

    strcpy(dev, ifr.ifr_name);
    return fd;
}

int main(int argc, char** argv) {

  char dev[IFNAMSIZ];
  int tun_fd;

  if (argc > 1) {
    assert(strlen(argv[1]) < IFNAMSIZ);
    strcpy(dev, argv[1]);
  } else {
    strcpy(dev, IFNAME);
  }

  printf("device name: %s\n", dev);

  tun_fd = tun_alloc(dev);

  int running = 1;

  uint8_t buf[BUFLEN];
  while (running) {
    int nread;

    if ((nread = read(tun_fd, buf, BUFLEN)) < 0) {
      perror("ERR: Read from tun_fd");
      break;
    }

    printf("Read %d bytes from device %s\n", nread, dev);
  }

  close(tun_fd);

  return EXIT_SUCCESS;
}
