C语言 如何从 unix c 中的 struct addrinfo 获取端口号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2371910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:43:36  来源:igfitidea点击:

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

cnetwork-programmingudpsockets

提问by sfactor

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.

我需要通过特定端口中的 UDP 将一些数据发送到远程服务器并从它接收响应。但是,它正在阻塞,我没有得到任何响应。我需要检查我从 中获得的 addrinfo 值getaddrinfo(SERVER_NAME, port, &hints, &servinfo)是否正确。

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

我知道inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s)给了我服务器 IP 地址。(我正在使用 Beej 指南中的方法。)

回答by David Gelhar

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

你做一些类似于 Beej 的 get_in_addr 函数所做的事情:

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

还要注意在sockaddr_in(或sockaddr_in6)结构中处理端口号的#1 陷阱:端口号总是以网络字节顺序存储。

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():

这意味着,例如,如果你打印出get_in_port()上面调用的结果,你需要抛出一个ntohs()

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