如何查找套接字的本地端口号?(Windows C++)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6659858/
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
How to find a socket's local port number? (Windows C++)
提问by Sefu
I'm new to Windows networking, and I am trying to find out which PORT number my socket is bound to (C++, Windows 7, Visual Studio 2010 Professional). It is a UDP socket, and from what I understand, using the following initial setup should bind it to a random available port/address:
我是 Windows 网络的新手,我试图找出我的套接字绑定到哪个端口号(C++、Windows 7、Visual Studio 2010 Professional)。它是一个 UDP 套接字,据我所知,使用以下初始设置应将其绑定到随机可用的端口/地址:
sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
local.sin_port = 0; //randomly selected port
int result = bind(clientSock, (sockaddr*)&local, sizeof(local));
//result is always 0
As far as using this method, it works for sending data or binding it to a specific port (replacing the 0 with a desired port number). What I need is to bind it randomly, and then find out which port it was bound to afterwards. Is there any way I can do this? It seems that the "local" struct contains "0.0.0.0" as the IP address and "0" as the PORT number.
就使用此方法而言,它适用于发送数据或将其绑定到特定端口(将 0 替换为所需的端口号)。我需要的是随机绑定它,然后找出它之后绑定到哪个端口。有什么办法可以做到这一点吗?似乎“本地”结构包含“0.0.0.0”作为IP地址和“0”作为端口号。
Thanks for any and all help! I appreciate it.
感谢您的任何帮助!我很感激。
回答by Adam Rosenfield
Use getsockname
. For example:
使用getsockname
. 例如:
struct sockaddr_in sin;
int addrlen = sizeof(sin);
if(getsockname(clientSock, (struct sockaddr *)&sin, &addrlen) == 0 &&
sin.sin_family == AF_INET &&
addrlen == sizeof(sin))
{
int local_port = ntohs(sin.sin_port);
}
else
; // handle error
This also works for *nix-based systems, but note that some systems define the third argument of getsockname
to be of type socklen_t*
instead of int*
, so you might get warnings about pointers differing in signedness if you're writing cross-platform code.
这也适用于基于 *nix 的系统,但请注意,某些系统将 的第三个参数定义getsockname
为类型socklen_t*
而不是int*
,因此如果您正在编写跨平台代码,您可能会收到有关签名不同的指针的警告。