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);
sharing knowledge earned into design/development/technical delicate and/or difficult situations ...
Labels
Gnu/Linux
(95)
Administration
(83)
StorageHardware
(17)
Programming
(16)
WebBrowser
(15)
General
(11)
GNU/Bash
(7)
Solaris
(7)
Virtualization
(7)
C
(6)
Domotics
(6)
Musics
(5)
Raspberry
(5)
Desktop
(4)
Java
(4)
VersionControlSystems
(4)
ArtificialIntelligence
(2)
Optimization
(2)
multimedia
(2)
Arduino
(1)
Electronics
(1)
LTS
(1)
MacOS
(1)
Mechanics
(1)
Processing
(1)
Robotics
(1)
Ubuntu
(1)
Upgrade
(1)
ez-robot
(1)
Great info !
ReplyDeleteHey is it possible to Add an interface in Cygwin in a similar way that you've coded for Linux ?
I've never tried but it might work although additional ioctl may be needed.
ReplyDeleteLet me know if you try.
So have you tried it ?
ReplyDelete