0

On my mac, I did a command line

ipconfig getifaddr en1

and it shows

10.0.0.2

However when I use the

struct ifaddrs *id;
int success=0;
success=getifaddrs(&id);
printf("Network Address of %s :- %d\n",id->ifa_name,id->ifa_addr);

it shows

Network Address of lo0 :- 8393376

So, how does the 10.0.0.2 relate to 8393376?

Seems like they don't match from the two ways of finding the IP address.

4

2 回答 2

1
 id->ifa_addr

是某种struct sockaddr(例如 a struct sockaddr_in),它包含地址的类型(例如 IPv4、IPv6、以太网 MAC 地址或类似地址),以及地址的二进制表示。它不是您可以使用 printf 的 %s 打印的字符串。

你也许可以使用这个:

void
print_sockaddr(struct sockaddr* addr,const char *name)
{
    char addrbuf[128] ;

    addrbuf[0] = 0;
    if(addr->sa_family == AF_UNSPEC)
        return;

    switch(addr->sa_family) {
    case AF_INET:
        inet_ntop(addr->sa_family,&((struct sockaddr_in*)addr)->sin_addr,
                  addrbuf,sizeof(struct sockaddr_in));
        break;
    case AF_INET6:
        inet_ntop(addr->sa_family, &((struct sockaddr_in6*)addr)->sin6_addr,
                  addrbuf,sizeof(struct sockaddr_in6));
        break;
    default:
        sprintf(addrbuf,"Unknown family (%d)",(int)addr->sa_family);
        break;

    }
    printf("%-16s %s\n",name,addrbuf);
}

...

print_sockaddr(id->ifa_addr,id->ifa_name);

getifaddrs 返回一个 的链表struct ifaddrs,代表每个接口。

你需要做:

struct ifaddrs *addrs,*tmp;

if(getifaddrs(&addrs) != 0) {
    perror("getifaddrs");
    return 1;
}
for(tmp = addrs; tmp ; tmp = tmp->ifa_next) {
    print_sockaddr(tmp->ifa_addr, tmp->ifa_name);
}
freeifaddrs(addrs);
于 2013-09-22T22:49:56.987 回答
0

伙计,要打印您需要的 IP,请执行以下操作:

struct sockaddr_in * ip;
ip = (struct sockaddr_in *) id->ifa_addr;

if (ip->sin_family == AF_INET)
    printf("Network Address: %s\n",inet_ntoa(ip->sin_addr));

尝试这样做。

于 2013-09-22T23:03:43.913 回答