gpt4 book ai didi

c - 尽管未设置 AI_PASSIVE,Getaddrinfo() 返回通配符地址

转载 作者:行者123 更新时间:2023-11-30 14:53:38 25 4
gpt4 key购买 nike

来自 getaddrinfo() 的手册页...

If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned socket addresses will be suitable for use with connect(2), sendto(2), or sendmsg(2).

但我在某些网站上返回了0.0.0.0。我不应该获得通配符地址吗?

void checkAddresses(char * addrName)
{
struct addrinfo hints;
struct addrinfo * infoptr = 0;
struct addrinfo * node = 0;
int gai_return = 0;
int socket_fd = 0;
int gni_return = 0;
char host_buffer[255] = { 0 };
struct sockaddr_in * h = 0;

memset(host_buffer, 0, sizeof(host_buffer));

memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;

gai_return = getaddrinfo(addrName, 0, &hints, &infoptr);
if(gai_return != 0)
{
perror("Getaddrinfo() failure");
exit(1);
}

for (node = infoptr; node != NULL; node = node->ai_next)
{
h = (struct sockaddr_in *) node->ai_addr;
strcpy(host_buffer, inet_ntoa(h->sin_addr));
puts(host_buffer);
}

freeaddrinfo(infoptr);
}

最佳答案

您指定了AF_UNSPEC,这意味着未指定的地址系列。 现在这意味着您将同时获得 AF_INETAF_INET6 。如果您想要的只是AF_INET,请直接说出来。

请注意,尤其是在查找 localhost 时,IPv6 地址 ::1 将具有二进制表示形式

00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01

现在,如果您将前 4 个字节重新解释为 IPv4 地址(如果将指针强制转换为 struct sockaddr_in * 就会发生这种情况)...

<小时/>

使用AF_UNSPEC,您必须检查node->ai_family;对于 IPv4 套接字,它是 AF_INET;对于 IPv6,它是 AF_INET6 - 也可能是其他东西。

但请注意,大多数时候您根本不会检查地址 - 没有必要。相反,您只需将未转换的 struct sockaddr *ai_addr 传递给 sendto (对于 UDP 套接字)。

关于c - 尽管未设置 AI_PASSIVE,Getaddrinfo() 返回通配符地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47109062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com