此代码将做的事:
#include
#include
#include /* For strncpy */
#include
#include
#include
#include
#include
#include
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;
}
结果:
192.168.5.27
RUN SUCCESSFUL (total time: 52ms)
或者,你也可以使用一个IP地址掩码。例如,如果面膜从255.0.0.0是不同的(回送面膜),这将只打印
#include
#include
#include
#include
#include
#include
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;
}
结果:
mask:255.255.255.0
eth0 IP Address 192.168.5.27
RUN SUCCESSFUL (total time: 53ms)