假设以下代码模仿resolveip
实用程序的基本功能:
#define _POSIX_SOURCE /* getaddrinfo() */
#include <sys/types.h> /* getaddrinfo(), struct addrinfo, struct sockaddr */
#include <sys/socket.h> /* getaddrinfo(), struct addrinfo, struct sockaddr, AF_* */
#include <netdb.h> /* getaddrinfo(), struct addrinfo, struct sockaddr */
#include <arpa/inet.h> /* inet_ntop() */
#include <stdio.h> /* fprintf(), printf(), perror(), stderr */
#include <stdlib.h> /* EXIT_SUCCESS */
int main(int argc, char** argv) {
for(int i = 1; i < argc; ++i) { /* For each hostname */
char* hostname = argv[i];
struct addrinfo* res; /* We retrieve the addresses */
if(getaddrinfo(hostname, NULL, NULL, &res) == -1) {
perror("getaddrinfo");
continue;
}
for(; res->ai_next; res = res->ai_next) { /* We print the addresses */
switch(res->ai_addr->sa_family) {
case AF_INET: {
struct in_addr addr = ((struct sockaddr_in*)(res->ai_addr))->sin_addr;
char buffer[17]; printf("%s: %s\n", hostname, inet_ntop(AF_INET, &addr, buffer, 17)); break;
} case AF_INET6: {
struct in6_addr addr = ((struct sockaddr_in6*)(res->ai_addr))->sin6_addr;
char buffer[40]; printf("%s: %s\n", hostname, inet_ntop(AF_INET6, &addr, buffer, 40)); break;
} default: {
fprintf(stderr, "%s: Unknown address family\n", hostname);
}
}
}
freeaddrinfo(res); /* We release the allocated resources */
} return EXIT_SUCCESS;
}
以google.com
作为第一个也是唯一参数调用的上述代码将输出类似于:
google.com: 173.194.35.87
google.com: 173.194.35.87
google.com: 173.194.35.87
google.com: 173.194.35.95
google.com: 173.194.35.95
google.com: 173.194.35.95
google.com: 173.194.35.88
google.com: 173.194.35.88
google.com: 173.194.35.88
google.com: 2a00:1450:4008:800::101f
google.com: 2a00:1450:4008:800::101f
假设我们想要摆脱重复的条目。因此,让我们创建一个结构,其中包含有关我们希望检索哪种结果的提示。以下修改不会以任何方式影响输出,因为结构已按照getaddrinfo(3)
联机帮助页的要求初始化为默认值:
struct addrinfo hints = {
.ai_family = AF_UNSPEC,
.ai_socktype = 0,
.ai_protocol = 0,
.ai_flags = (AI_V4MAPPED | AI_ADDRCONFIG)
}; if(getaddrinfo(hostname, NULL, &hints, &res) == -1) {
perror("getaddrinfo");
continue;
}
现在让我们通过将ai_socktype
字段指定为任意值来过滤掉重复的条目:
struct addrinfo hints = {
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_DGRAM,
.ai_protocol = 0,
.ai_flags = (AI_V4MAPPED | AI_ADDRCONFIG)
};
唉,我们现在丢失了IPv6地址:
google.com: 173.194.35.87
google.com: 173.194.35.95
google.com: 173.194.35.88
现在让我们回到原来的无提示版本:
if(getaddrinfo(hostname, NULL, NULL, &res) == -1) {
perror("getaddrinfo");
continue;
}
现在让我们使用手动过滤:
for(; res->ai_next; res = res->ai_next) {
if(res->ai_socktype != SOCK_DGRAM) continue;
...
}
现在一切都按照预期的方式运作:
google.com: 173.194.35.87
google.com: 173.194.35.95
google.com: 173.194.35.88
google.com: 2a00:1450:4008:801::101f
我很好奇,因为提示传递给getaddrinfo(3)
函数和手动过滤返回的记录之间存在差异。使用glibc 2.17在linux内核3.8.0-32上测试。
答案 0 :(得分:4)
您的for循环检查错误,您总是跳过最后一个条目 - 在您的情况下恰好是IPv6地址。
for(; res->ai_next; res = res->ai_next) {
需要
for(; res; res = res->ai_next) {