How to get the port number from struct addrinfo in unix c

c, network-programming, sockets, udp

Solution

You do something similar to what Beej's get_in_addr function does:

// get port, IPv4 or IPv6:
in_port_t get_in_port(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET)
        return (((struct sockaddr_in*)sa)->sin_port);

    return (((struct sockaddr_in6*)sa)->sin6_port);
}

Also beware of the #1 pitfall dealing with port numbers in `sockaddr_in` (or `sockaddr_in6`) structures: port numbers are always stored in network byte order.

That means, for example, that if you print out the result of the `get_in_port()`call above, you need to throw in a `ntohs()`:

printf("port is %d\n", ntohs(get_in_port((struct sockaddr *)p->ai_addr)));

Problem

I need to send some data to a remote server via UDP in a particular port and get receive a response from it. However, it is blocking and I do not get any response. I need to check if the addrinfo value that I get from the `getaddrinfo(SERVER_NAME, port, &hints, &servinfo)` is correct or not. How do I get the port number from this data structure? I know `inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s)` gives me server IP address. (I am using the method in Beej's guide.)

Original source