如何找到套接字的本地端口号? (Windows C ++) [英] How to find a socket's local port number? (Windows C++)

查看:396
本文介绍了如何找到套接字的本地端口号? (Windows C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Windows网络的新手,我试图找出我的套接字绑定到哪个端口号(C ++,Windows 7,Visual Studio 2010 Professional).它是UDP套接字,据我了解,使用以下初始设置应将其绑定到随机可用的端口/地址:

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:

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

就使用此方法而言,它可用于发送数据或将其绑定到特定端口(将0替换为所需的端口号).我需要的是随机绑定它,然后找出它随后绑定到哪个端口.有什么办法可以做到吗?似乎本地"结构包含IP地址"0.0.0.0"和端口号"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.

感谢所有帮助!我很感激.

Thanks for any and all help! I appreciate it.

推荐答案

使用

Use getsockname. For example:

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

这也适用于基于* nix的系统,但是请注意,某些系统将getsockname的第三个参数定义为socklen_t*类型,而不是int*类型,因此如果出现以下情况,您可能会收到有关指针签名不同的警告:您正在编写跨平台代码.

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.

这篇关于如何找到套接字的本地端口号? (Windows C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆