开发者

Find a free port

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:

  • How does IPEndPoint find a free port when I do new IPEndPoint(IPAddress.Any, 0), for exampl开发者_Go百科e?

  • 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.


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.

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜