Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 455
sfactor Avatar asked Mar 03 '10 14:03

sfactor


People also ask

What does getaddrinfo do in c?

In C programming, the functions getaddrinfo() and getnameinfo() convert domain names, hostnames, and IP addresses between human-readable text representations and structured binary formats for the operating system's networking API.

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)

What is Ai_flags?

ai_flags. Type: int. Flags that indicate options used in the getaddrinfo function. Supported values for the ai_flags member are defined in the Ws2def. h header file on the Windows SDK for Windows 7 and later.

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

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)));
like image 75
David Gelhar Avatar answered Sep 24 '22 03:09

David Gelhar