获取以太网指定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主以太网地址: 1.0.0.0
2016-10-26 04:37:52 UTC主以太网eth0 ip: 2.0.0.0
问题:
lo的ip应该是127.0.0.1,eth0的ip不应该是2.0.0.0,对吗?
发布于 2016-10-26 05:01:59
您已经假定您遇到的第一个名称条目将在AF_INET家族中,但您没有检查。
使用ips->ifa_addr->sa_family检查它是否是AF_INET。
您遇到的第一个lo和eth0设备很可能是AF_PACKET家族中的。
https://stackoverflow.com/questions/40253904
复制相似问题