Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 example?

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

like image 505
Alon Gubkin Avatar asked Mar 16 '10 17:03

Alon Gubkin


People also ask

What ports are free?

Ports 49152-65535– These are used by client programs and you are free to use these in client programs. When a Web browser connects to a web server the browser will allocate itself a port in this range.

How do I find out what ports are available?

Open “Terminal”. Type the netstat -a | grep -i “listen” command and press “Enter” to see the list of opened ports.

How do I find unused ports on my server?

You can use "netstat" to check whether a port is available or not. Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.


1 Answers

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.

like image 57
Lucero Avatar answered Sep 21 '22 13:09

Lucero