gpt4 book ai didi

c - 为什么 getaddrinfo 返回 HTTP 端口号 20480?

转载 作者:行者123 更新时间:2023-12-02 00:16:18 25 4
gpt4 key购买 nike

这是我的代码。

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int main()
{
struct addrinfo *ai, *p;

if (getaddrinfo("localhost", "http", NULL, &ai) != 0) {
printf("error\n");
return EXIT_FAILURE;
}

for (p = ai; p != NULL; p = p->ai_next)
{
if (p->ai_family == AF_INET) {
struct sockaddr_in *addr = (struct sockaddr_in *) p->ai_addr;
printf("IPv4 port: %d\n", addr->sin_port);
} else if (p->ai_family == AF_INET6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) p->ai_addr;
printf("IPv6 port: %d\n", addr->sin6_port);
}
}

return 0;
}

这是输出。

$ gcc -std=c99 -D_POSIX_SOURCE -Wall -Wextra -pedantic foo.c
$ ./a.out
IPv6 port: 20480
IPv6 port: 20480
IPv4 port: 20480
IPv4 port: 20480

我预计端口号为 80。为什么我在输出中看到 20480?

最佳答案

端口按网络顺序返回。尝试调用 ntohs(addr->sin_port)

查看反转的字节顺序:

0x5000 = 20480

0x0050 = 80

关于c - 为什么 getaddrinfo 返回 HTTP 端口号 20480?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434134/

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