gpt4 book ai didi

c - 我用 getifaddrs 得到错误的 IP 地址

转载 作者:太空狗 更新时间:2023-10-29 12:25:59 30 4
gpt4 key购买 nike

获取以太网指定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;
}

主要用于:

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 ] 以太网 lo ip: 1.0.0.0
[ 2016-10-26 04:37:52 UTC ] [ server_info.cpp:91 ] [ main ] ethernet eth0 ip: 2.0.0.0

问题:
lo 的 ip 应该是 127.0.0.1eth0 的 ip 不应该是 2.0.0.0,我对吗?

最佳答案

您假设您遇到的第一个名称条目将在 AF_INET 系列中,但您没有检查。

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

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

关于c - 我用 getifaddrs 得到错误的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40253904/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com