This code will do the following:
#include <stdio.h> #include <unistd.h> #include <string.h> /* For strncpy */ #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <arpa/inet.h> int main() { int fd; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); /* I want to get an IPv4 IP address */ ifr.ifr_addr.sa_family = AF_INET; /* I want an IP address attached to "eth0" */ strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1); ioctl(fd, SIOCGIFADDR, &ifr); close(fd); /* Display result */ printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); return 0; }
Result:
192.168.5.27 RUN SUCCESSFUL (total time: 52ms)
Alternatively, you can also use an IP address mask. For example, this will be printed only if the mask is different from 255.0.0.0 (loop mask)
#include <stdio.h> #include <sys/types.h> #include <ifaddrs.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> int main(int argc, const char * argv[]) { struct ifaddrs * ifAddrStruct = NULL, * ifa = NULL; void * tmpAddrPtr = NULL; getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (ifa ->ifa_addr->sa_family == AF_INET) { // Check it is IPv4 char mask[INET_ADDRSTRLEN]; void* mask_ptr = &((struct sockaddr_in*) ifa->ifa_netmask)->sin_addr; inet_ntop(AF_INET, mask_ptr, mask, INET_ADDRSTRLEN); if (strcmp(mask, "255.0.0.0") != 0) { printf("mask:%s\n", mask); // Is a valid IPv4 Address tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); } else if (ifa->ifa_addr->sa_family == AF_INET6) { // Check it is // a valid IPv6 Address. // Do something } } } if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct); return 0; }
Result:
mask:255.255.255.0 eth0 IP Address 192.168.5.27 RUN SUCCESSFUL (total time: 53ms)
4pie0 source share