获取以太网指定IP地址的功能:
char *get_ethernet_ip(const char *ethernet, char *ip, size_t len) {
struct ifaddrs *ips;
int rc = getifaddrs(&ips);
if (rc == -1) {
SYSLOG("getifaddrs() failed (%s)", strerror(errno));
return NULL;
}
for (; ips != NULL; ips = ips->ifa_next) {
if (strcasecmp(ethernet, ips->ifa_name) == 0) {
in_addr local_ip = ((sockaddr_in *)ips->ifa_addr)->sin_addr;
const char *p = inet_ntop(AF_INET, &local_ip, ip, len);
if (p == NULL) {
SYSLOG("inet_ntop() failed (%s)", strerror(errno));
return NULL;
}
return ip;
}
}
return NULL;
}
在main中使用:
char ip[32];
SYSLOG("ethernet lo ip: %s", get_ethernet_ip("lo", ip, 32));
SYSLOG("ethernet eth0 ip: %s", get_ethernet_ip("eth0", ip, 32));
结果:
[2016-10-26 04:37:52 UTC] [server_info.cpp:90] [main] ethernet lo ip:1.0.0.0
[2016-10-26 04:37:52 UTC] [server_info.cpp:91] [主要]以太网eth0 ip:2.0.0.0
问题:
lo
的IP应该是127.0.0.1
,eth0
的IP应该是2.0.0.0
,我是对的吗?
答案 0 :(得分:1)
您认为您在姓名中遇到的第一个条目将在AF_INET
系列中,但您没有检查。
使用ips->ifa_addr->sa_family
检查它是AF_INET
。
您遇到的第一个lo
和eth0
设备可能属于AF_PACKET
系列。