我试图了解 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 等) 的含义?我读过这个人,但没有什么。
我还想知道是否可以提供 IPv6 地址(例如 ::1)并且函数返回名称:localhost?
非常感谢 !!