这是我的代码。
#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呢?
答案 0 :(得分:8)
端口按网络顺序返回。尝试拨打#include <iostream>
struct always_10
{
constexpr static double value() { return 10.0; }
};
template <class X>
void show_x()
{
constexpr auto x = X::value();
std::cout<<"x is always "<< x <<" in the entire program."<<std::endl;
}
template<class X>
void show_x(X x_)
{
constexpr auto x = x_.value();
std::cout<<"x is always "<< x <<" in the entire program."<<std::endl;
}
int main()
{
show_x<always_10>();
show_x(always_10());
return 0;
}
请参见反向字节顺序:
0x5000 = 20480
0x0050 = 80