如何找到分配给 UDP 客户端的端口号(在 .net/C# 中)? [英] How do I find the port number assigned to a UDP client (in .net/C#)?
问题描述
如果我使用
var socket = new UdpClient(0,AddressFamily.InterNetwork);
然后我如何找到套接字的端口?
How do I then find the port of the socket?
我可能是愚蠢的,但我在 MSDN/Google 上运气不佳(可能是因为星期五是 4:42 并且阳光明媚).
I'm probably being daft, but I'm not having luck in MSDN/Google (probably because it is 4:42 on a Friday and the sun is shining).
背景:
我想要做的是找到一个开放的端口,然后向另一个进程报告在该端口上将消息转发给我.可能有多个客户端,所以我不想使用固定端口.
What I want to do is find an open port, and then report to another process to forward messages to me on that port. There may be multiple clients, so I don't want to used a fixed port.
谢谢.
推荐答案
UdpClient 是 Socket 类的包装器,它通过 LocalEndPoint 属性公开它绑定到的端点.由于您使用的是 UDP/IP 客户端,因此它是一个具有所需端口属性的 IPEndPoint:
UdpClient is a wrapper around the Socket class which exposes the endpoint it's bound to through the LocalEndPoint property. Since you're using an UDP/IP client it's an IPEndPoint which has the desired Port property:
int port = ((IPEndPoint)socket.Client.LocalEndPoint).Port;
这篇关于如何找到分配给 UDP 客户端的端口号(在 .net/C# 中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!