我用getifaddrs得到了错误的ip地址

时间:2016-10-26 04:44:22

标签: c linux

获取以太网指定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.1eth0的IP应该是2.0.0.0,我是对的吗?

1 个答案:

答案 0 :(得分:1)

您认为您在姓名中遇到的第一个条目将在AF_INET系列中,但您没有检查。

使用ips->ifa_addr->sa_family检查它是AF_INET

您遇到的第一个loeth0设备可能属于AF_PACKET系列。