如何查找套接字的本地端口号? (Windows C ++)

时间:2022-12-15 15:10:50

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网络的新手,我试图找出我的套接字绑定到哪个PORT编号(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)。我需要的是随机绑定它,然后找出它之后绑定的端口。有什么方法可以做到这一点吗?似乎“local”结构包含“0.0.0.0”作为IP地址,“0”作为PORT编号。

Thanks for any and all help! I appreciate it.

感谢您的帮助!我很感激。

2 个解决方案

#1


16  

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 *类型,因此如果您正在编写跨平台,则可能会收到有关签名不同的指针的警告码。

#2


1  

getsockname might get it for you, but I wonder why your code works with a UDP socket.

getsockname可能会为你得到它,但我想知道为什么你的代码使用UDP套接字。

#1


16  

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 *类型,因此如果您正在编写跨平台,则可能会收到有关签名不同的指针的警告码。

#2


1  

getsockname might get it for you, but I wonder why your code works with a UDP socket.

getsockname可能会为你得到它,但我想知道为什么你的代码使用UDP套接字。