我正在尝试理解getaddrinfo函数返回的内容:
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
int main (int argc, char *argv[])
{
struct addrinfo *res = 0 ;
getaddrinfo("localhost", NULL ,NULL,&res);
printf("ai_flags -> %i\n", res->ai_flags) ;
printf("ai_family -> %i\n", res->ai_family) ;
printf("ai_socktype -> %i\n", res->ai_socktype) ;
printf("ai_protocol -> %i\n", res->ai_protocol) ;
printf("ai_addrlen -> %i\n", res->ai_addrlen) ;
struct sockaddr_in* saddr = (struct sockaddr_in*)res->ai_addr;
printf("ai_addr hostname -> %s\n", inet_ntoa(saddr->sin_addr));
freeaddrinfo(res);
return 0 ;
}
结果:
ai_flags -> 40
ai_family -> 2
ai_socktype -> 1
ai_protocol -> 6
ai_addrlen -> 16
ai_addr hostname -> 127.0.0.1
在/etc/hosts中,我得到了:
127.0.0.1 localhost
::1 localhost
Getaddrinfo仅返回127.0.0.1,而不是::1?我不明白为什么?
第二个问题是在哪里可以找到这些整数(40,2,1,6等)的含义?我读过这个人,但什么也没读到。
我还想知道是否可以给出一个本地地址(例如::1),并且函数返回名称: IPv6?
非常感谢!
发布于 2011-05-11 05:14:55
res
还包含字段struct addrinfo *ai_next;
,它是指向getaddrinfo
找到的其他条目的指针,如果没有其他条目,则为NULL。如果检查res->ai_next
,您应该会找到IPv6条目。
至于struct addrinfo
中的整型字段,它们对应于具有实现定义的值的预定义常量,并且整数值本身并不是人们通常感兴趣的。如果您想知道给定字段的含义,请将其与可以分配给该字段的常量(对于ai_socktype
为SOCK_STREAM
、SOCK_DGRAM
等;对于ai_protocol
为IPPROTO_TCP
、IPPROTO_UDP
等;等等)进行比较;或者对于ai_flags
,测试与预定义常量对应的每一位(例如,if (res->ai_flags & AI_NUMERICHOST) {printf("ai_flags has AI_NUMERICHOST\n"); }
)。
发布于 2011-05-11 05:16:04
extern struct sockaddr_in6 create_socket6(int port, const char * address) {
struct addrinfo hints, *res, *resalloc;
struct sockaddr_in6 input_socket6;
int errcode;
/* 0 out our structs to be on the safe side */
memset (&hints, 0, sizeof (hints));
memset (&input_socket6, 0, sizeof(struct sockaddr_in6));
/* We only care about IPV6 results */
hints.ai_family = AF_INET6;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_DEFAULT;
errcode = getaddrinfo (address, NULL, &hints, &res);
if (errcode != 0)
{
perror ("[ERROR] getaddrinfo ");
return input_socket6;
}
resalloc = res;
while (res)
{
/* Check to make sure we have a valid AF_INET6 address */
if(res->ai_family == AF_INET6) {
/* Use memcpy since we're going to free the res variable later */
memcpy (&input_socket6, res->ai_addr, res->ai_addrlen);
/* Here we convert the port to network byte order */
input_socket6.sin6_port = htons (port);
input_socket6.sin6_family = AF_INET6;
break;
}
res = res->ai_next;
}
freeaddrinfo(resalloc);
return input_socket6;
}
下面是一些解释它的代码。基本上,除非你给getaddrinfo一些提示,告诉它只与IPV6一起工作,否则它也会给出IPV4结果。这就是为什么您必须循环遍历结果,如下所示。
https://stackoverflow.com/questions/5956516
复制相似问题