0

I have written the following function that is supposed to create a TUN interface named "my_tun" on Linux:

int tun_open()
{
  int fd;
  if ((fd = open("/dev/net/tun", O_RDWR)) == -1) {
    return -1;
  }

  struct ifreq ifr;
  strncpy(ifr.ifr_name, "my_tun", IFNAMSIZ);
  ifr.ifr_flags = IFF_TUN | IFF_NO_PI;

  if (ioctl(fd, TUNSETIFF, &ifr) == -1) {
    return -1;
  }

  return fd;
}

I'm testing it by running it inside a Ubuntu docker container started with --cap-add NET_ADMIN. Inside this docker container I first execute:

mkdir /dev/net
mknod /dev/net/tun c 10 200

And the run my function. The latter does not fail yet afterwards ifconfig does not show a TUN interface, only an ethernet and a loopback interface. What am I doing wrong?

Peter
  • 2,919
  • 1
  • 16
  • 35

3 Answers3

0

I recommend you to check the source code of ifconfig tool. It should contain correct code to create tun devices. Use it as reference.

Most probably, the newest edition of "UNIX Network Programming" (Stevens et al.) should have a description somewher on how to create a tun device also.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31
0

Try "ip link" and you might see it there provided code above didn't return -1. Also your interface is non-persistent therefore you need to keep the program running when u try ifconfig or IP link. Try to add a sleep before "return fd" to buy time and see if that helps.

vtewari
  • 23
  • 4
0

By using the code you provided, a non persistent TUN interface would be created and, after your program exits, the TUN interface will be destroyed.

You can make it persistent by adding this to your code:

int result = ioctl(fd, TUNSETPERSIST, 1);
if (result == -1)
{
    printf("Unable to make TUN interface persistent\n");
}

Make sure to include if_tun.h for TUNSETPERSIST.

pmacfarlane
  • 3,057
  • 1
  • 7
  • 24