开发者

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) giv开发者_如何转开发es me server IP address. (I am using the method in Beej's guide.)


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)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜