假设我正在运行一个名为 IpAddresses.c 的程序。我希望该程序根据每个接口(interface)获取该设备拥有的所有 IP 地址。就像ifconfig .我该怎么做?
我不太了解ioctl ,但我读了它可能对我有帮助。
最佳答案
只需使用 getifaddrs() .这是一个例子:
#include <arpa/inet.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <stdio.h>
int main ()
{
struct ifaddrs *ifap, *ifa;
struct sockaddr_in *sa;
char *addr;
getifaddrs (&ifap);
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr && ifa->ifa_addr->sa_family==AF_INET) {
sa = (struct sockaddr_in *) ifa->ifa_addr;
addr = inet_ntoa(sa->sin_addr);
printf("Interface: %s\tAddress: %s\n", ifa->ifa_name, addr);
}
}
freeifaddrs(ifap);
return 0;
}
这是我在我的机器上得到的输出:
Interface: lo Address: 127.0.0.1
Interface: eth0 Address: 69.72.234.7
Interface: eth0:1 Address: 10.207.9.3
关于c - 我怎样才能知道 C 中接口(interface)的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139405/