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?
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
0as 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.