Lone Learner Lone Learner - 1 year ago 117
C Question

Why does getaddrinfo return a port number of 20480 for HTTP?

Here is my code.

#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) {

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;

Here is the output.

$ 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

I was expecting the port number to be 80. Why do I see 20480 in the output then?

Answer Source

The port is returned in network order. Try calling ntohs(addr->sin_port)

See the reversed byte order:

0x5000 = 20480

0x0050 = 80

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download