查找自由港 [英] Find a free port

查看:142
本文介绍了查找自由港的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个FTP服务器库(因为我需要它,我无法找到这什么好的解决办法),在C#中,我有两个问题:

I'm writing an FTP server library (because I need it and I can't find any good solutions for this) in C# and I have two questions:

  • 如何 IPEndPoint 发现,当我做自由港新IPEndPoint(IPAddress.Any,0)例如?

  • How does IPEndPoint find a free port when I do new IPEndPoint(IPAddress.Any, 0), for example?

是否有可能找到一个空闲的端口从一个范围(例如,从1023到65535),没有 GetActiveTcpConnections 方法?因为它是缓慢的 - 我需要一个更快的方法来做到这一点

Is it possible to find a free port from a range (for example from 1023 to 65535), without the GetActiveTcpConnections method? Because it is slow - I need a faster way to do this.

推荐答案

一旦你开始听一个未分配的端口(0),它将由操作系统(或者,更$ P $分配pcisely,由上TCP / IP协议栈)。由于堆栈管理所有的端口,它可以指定一个免费的。

As soon as you start listening on an unassigned port (0), it will be assigned by the operating system (or, more precisely, by the TCP/IP stack). Since the stack manages all the ports, it can assign a free one.

所以,刚开始你的连接听录音,然后检查端口的<一个href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.localendpoint.aspx">LocalEndpoint属性以将其传递到客户端。该的TcpListener文档包含更多相关信息。

So just start to listen on your connection and then check the port in the LocalEndpoint property to pass it to the client. The TcpListener documentation contains more information about this.

如果你需要找到一个自由的范围内,你只需要遍历品种齐全,尝试启动监听每一个。如果你成功了,你找到了一个空闲端口,你可以退出你的循环;如果没有,就继续循环。这是唯一可靠的方法来做到这一点,否则你会遇到的竞争条件与其他进程或您的这两种评价相同的自​​由港,并第一次使用它赢,即使线程,而另外code将无法使用的端口

If you need to find a free one in a range, you just have to loop over the full range and try to start listening on each one. If you succeed, you found a free port and you can exit your loop; if not, just continue with the loop. This is the only reliable way to do it because otherwise you can run into a race condition with other processes or even threads of yours which both evaluate the same free port and the first to use it "wins", while the other code will not be able to use the port.

这篇关于查找自由港的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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