Search code examples
clinuxinterface

How to set the IP address from C in linux


By using strace and ifconfig, I found that I can set the IP address this way:

#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <string.h>

int main(int argc, const char *argv[]) {
    struct ifreq ifr;
    const char * name = "eth1";
    int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

    strncpy(ifr.ifr_name, name, IFNAMSIZ);

    ifr.ifr_addr.sa_family = AF_INET;
    inet_pton(AF_INET, "10.12.0.1", ifr.ifr_addr.sa_data + 2);
    ioctl(fd, SIOCSIFADDR, &ifr);

    inet_pton(AF_INET, "255.255.0.0", ifr.ifr_addr.sa_data + 2);
    ioctl(fd, SIOCSIFNETMASK, &ifr);

    ioctl(fd, SIOCGIFFLAGS, &ifr);
    strncpy(ifr.ifr_name, name, IFNAMSIZ);
    ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);

    ioctl(fd, SIOCSIFFLAGS, &ifr);

    return 0;
}

But I am not very happy with this solution:

inet_pton(AF_INET, "10.12.0.1", ifr.ifr_addr.sa_data + 2);

What is the "right" way of doing this?


Solution

  • The "correct" way for IPv4 without magic +2:

    struct sockaddr_in* addr = (struct sockaddr_in*)&ifr.ifr_addr;
    inet_pton(AF_INET, "10.12.0.1", &addr->sin_addr);
    

    To use IPv6, cast it to sockaddr_in6