23 September 2007

Add network interface under GNU/Linux

It is not so hard to perform it under GNU/Linux with alias.
The aim, is to add an alias to an existing network interface with the wished inet, broadcast and netmask addresses:
N.B.: All checks have been removed for better legibility, but it is very important to check returned code after each request.

// We consider the existence of the variables (unsigned char *) "aliasInterfaceName", "inetAddress", "broadcastAddress" and "netmaskAddress" which could be respectively "eth0:myAlias"; "192.168.80.1", "192.168.80.255" and "255.255.255.0" for instance.

int sd;
struct sockaddr_in *addr;
struct ifreq ifr, ifrBroadcast, ifrNetmask;

sd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));

// Add alias.
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.lifr_name, aliasInterfaceName, sizeof(ifr.ifr_name));
addr = (struct sockaddr_in *) &(ifr.ifr_addr);
addr->sin_family=AF_INET;
addr->sin_addr.s_addr=inet_addr(inetAddress);
ioctl(sd, SIOCSIFADDR, &ifr);

// Manages broadcast.
memset(&ifrBroadcast, 0, sizeof(ifrBroadcast));
strncpy(ifrBroadcast.lifr_name, aliasInterfaceName, sizeof(ifrBroadcast.ifr_name));
addr = (struct sockaddr_in *) &(ifrBroadcast.ifr_addr);
addr->sin_family=AF_INET;
addr->sin_addr.s_addr=inet_addr(broadcastAddress);
ioctl(sd, SIOCSIFBRDADDR, &ifrBroadcast)

// Manages netmask.
memset(&ifrNetmask, 0, sizeof(ifrNetmask));
strncpy(ifrNetmask.lifr_name, aliasInterfaceName, sizeof(ifrNetmask.ifr_name));
addr = (struct sockaddr_in *) &(ifrNetmask.ifr_addr);
addr->sin_family=AF_INET;
addr->sin_addr.s_addr=inet_addr(netmaskAddress);
ioctl(sd, SIOCSIFNETMASK, &ifrNetmask);

close(sd);

3 comments:

  1. Great info !

    Hey is it possible to Add an interface in Cygwin in a similar way that you've coded for Linux ?

    ReplyDelete
  2. I've never tried but it might work although additional ioctl may be needed.

    Let me know if you try.

    ReplyDelete

Thank you for your visit, let's share your point of view: