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.)
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.
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)
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.
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, ...
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With