Possible Duplicate:
On localhost, how to pick a free port number?
My requirement is different from this question.
On localhost, how to pick a free port number?
I am writing a test setup of another process using python. The other process needs a port number to be passed (say as a command line parameter). I cannot hard-code some random port number because many users usually would run same test in the same box. Now, how do I select a free port in python?
Edit:
I am not creating a socket in python. I just need to pass a number to some other process as a command line argument.
From DRH's answer, I could create a dummy socket, get its port number, close it and pass to the actual process. Is there any better way to do this?
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.
Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind() .
Well-Known Ports. Port numbers can run from 0 to 65353. Port numbers from 0 to 1023 are reserved for common TCP/IP applications and are called well-known ports.
There likely is not a safe way to do what you're asking. Even if the OS could return a port to you that is currently free, there's no guarantee that another process wouldn't bind a socket to that port between the time where you request the port and when the application you invoke attempts to bind to it.
Given that, if you're just looking for a port that is likely free, you could bind to port 0
as described here On localhost, how to pick a free port number?, close the resulting socket (freeing the port), and then pass that value to your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With