本文来告诉大家如何可以获取一个可用的端口
使用如下代码可以返回一个可用的端口
public static int GetAvailablePort(IPAddress ip) { TcpListener l = new TcpListener(ip, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return port; }
在调用 Stop 方法的时候,将可以重复使用此端口,同时在系统分配里面,在一段时间内不会再次被使用,因此这个端口是安全的,可以在这里进行使用
另一个方式是使用更底层的 Socket 类型,代码如下
public static int GetAvailablePort(IPAddress ip) { using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(ip, 0)); socket.Listen(1); var ipEndPoint = (IPEndPoint)socket.LocalEndPoint; var port = ipEndPoint.Port; return port; }
参阅 MiSeCo #12: Find free TCP port in the system - Michal Dymel - DevBlog
.net - In C#, how to check if a TCP port is available? - Stack Overflow

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。 欢迎转载、使用、重新发布,但务必保留文章署名 林德熙 (包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我 联系。