Sunday, October 14, 2012

TO get/set an IP address from Linux over the socket:
int s;
    struct ifreq ifr = {};

    s = socket(PF_INET, SOCK_DGRAM, 0);

    strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name));

    if (ioctl(s, SIOCGIFADDR, &ifr) >= 0)
          inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

ioctl call receives data from the kernel for SIOCGIFADDR for IP address.

In case of static IP address, we will set the IP address with ioctl( SIOCGIFADDR, socketDetails) call.
ioctl is the module which can be used for kernel/user or user to kernel communication. 
 For more, read Richard Steven's Unix Network Programming book

No comments: