Finding an available network port on the machine
- by Tomer Vromen
I'm trying to implement a simple FTP server (a variation of the EFTP protocol) in linux. When a client connects and sends the PASV command, the server should respond with a port number, so the client can connect to that port to transmit the file. How can the server choose a port number? Do I need to iterate through all the ports from 1024 to 65535 until I find a port that the process can bind to?
I know that calling bind() with 0 as the port automatically chooses the port to bind to, but then how can I know which port was chosen?
Many thanks.