Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

sockets

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) {
        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;
}

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?

like image 593
Lone Learner Avatar asked Sep 11 '16 08:09

Lone Learner


People also ask

What does getaddrinfo return?

The getaddrinfo() function translates the name of a service location (for example, a host name) and/or service name and returns a set of socket addresses and associated information to be used in creating a socket with which to address the specified service.

What does the function getaddrinfo () do?

The getaddrinfo function can be used to convert a text string representation of an IP address to an addrinfo structure that contains a sockaddr structure for the IP address and other information.

What is Ai_family?

ptr->ai_family is just an integer, a member of a struct addrinfo. ( And if you are wondering about the particular syntax of ptr-> , you can go through this question ), it will have a value of either AF_INET or AF_INET6 (Or in theory any other supported protocol)

Why is Addrinfo a linked list?

There are several reasons why the linked list may have more than one addrinfo structure, including: the network host is multihomed, accessible over multiple protocols (e.g., both AF_INET and AF_INET6); or the same service is available from multiple socket types (one SOCK_STREAM address and another SOCK_DGRAM address, ...


1 Answers

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

See the reversed byte order:

0x5000 = 20480

0x0050 = 80

like image 171
Shloim Avatar answered Oct 02 '22 09:10

Shloim