Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an interface programmatically on Linux?

How to add any interface programmatically on Linux?

Is there any way, to add eth, loop or tun interface? Can it be done via netlink?

Language is C++, OS is Ubuntu.

like image 624
Frederic Blase Avatar asked Sep 08 '26 12:09

Frederic Blase


1 Answers

The way to add an interface depends on the kind of interface. A tun or tap interface for example is created by opening /dev/net/tun and setting a few ioctls on the file descriptor you obtain. Here's a minimal example from the Linux kernel documentation:

  #include <linux/if.h>
  #include <linux/if_tun.h>

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

      if( (fd = open("/dev/net/tun", O_RDWR)) < 0 )
         return tun_alloc_old(dev);

      memset(&ifr, 0, sizeof(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_TUN; 
      if( *dev )
         strncpy(ifr.ifr_name, dev, IFNAMSIZ);

      if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
         close(fd);
         return err;
      }
      strcpy(dev, ifr.ifr_name);
      return fd;
  }              
like image 86
Joni Avatar answered Sep 11 '26 02:09

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!