【发布时间】:2016-09-16 18:01:48
【问题描述】:
我编写了以下测试程序,但无法理解我得到的输出:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
int main(int argc, char** argv) {
struct addrinfo* results;
struct addrinfo hints;
char buf[INET6_ADDRSTRLEN+1];
if (argc != 2) {
exit(-1);
}
memset((char*) &hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
int ret = getaddrinfo(NULL, argv[1], &hints, &results);
if (ret) {
fprintf(stderr, "%s\n", gai_strerror(ret));
exit(-1);
}
for (struct addrinfo* ai = results; ai != NULL; ai = ai->ai_next) {
if (ai->ai_family == AF_INET) {
inet_ntop(AF_INET, ai, buf, INET_ADDRSTRLEN);
} else {
inet_ntop(AF_INET6, ai, buf, INET6_ADDRSTRLEN);
}
printf("%s\n", buf);
}
freeaddrinfo(results);
return 0;
}
在我的 Fedora 23 机器上,这将打印:
1.0.0.0
100:0:a00:0:100:0:600:0
我的理解是返回的IP地址应该是INADDR_ANY和IN6ADDR_ANY_INIT,两者的值都应该是0,即预期的输出应该是0.0.0.0和::0。有人可以向我解释这里发生了什么吗?
另一个相关的问题是,如果我的一个接口有一个host.domain.dom 解析到的 IP,并且我不能先验地确定该域是否有 IPv6 地址,我怎样才能获得 sockaddr 结构,我可以用来侦听此域的 IPv4 和 IPv6 地址,但不绑定到任何其他 IP?即使AI_PASSIVE 标志在这种情况下被忽略,向getaddrinfo 提供该主机名是否正确?
【问题讨论】:
标签: sockets unix unix-socket