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 get not response. I needed 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 ip address and port number from this data structure. i know that inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),s, sizeof s)
gives me server IP address but i also need to make sure the port number is correct. (I am using the method in Beej's guide.)
views:
327answers:
1
+2
A:
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 scokaddr_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)));
David Gelhar
2010-03-03 14:42:46
this seems to work...i see that the port is correct, however i get a "Error receiving in UDP: Connection refused" when i try to get a response from the server. why would such a problem arise? i tried connected UDP
sfactor
2010-03-03 14:50:55
"Connection refused" typically means there is no process listening on the destination port you specified. It may also indicate that there's a firewall preventing you from sending to that server/port.
David Gelhar
2010-03-03 15:37:11