15

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?

Community
  • 1
  • 1
balki
  • 26,394
  • 30
  • 105
  • 151
  • 4
    In what way is your requirement different? – wim Dec 22 '11 at 06:25
  • 1
    I am not creating a socket in python. So How do I ask the OS to give a free port? I just need to pass that number to some other process as a command line argument. – balki Dec 22 '11 at 07:06
  • I'm not sure about asking the OS for a free port number. What if you ask multiple times without opening the sockets? Is it guaranteed that you'll get different port numbers on each request? – jcollado Dec 22 '11 at 07:21
  • after I ask once and run my process on that port. It no longer would be free. so would I not get a different port for a different process ? – balki Dec 22 '11 at 09:18
  • @balki - even if the OS told you a free port now, there's no guarantee that it will be free 100 milliseconds from now. At least with the "grab a port" approach, there should be a timeout before that port is next bound to a server socket. – kdgregory Dec 22 '11 at 13:12
  • But, since port numbers without an actual bound socket are meaningless, a better solution to your problem would seem to be making whatever application actually binds the port tell the rest of the world what that port is. – kdgregory Dec 22 '11 at 13:12

1 Answers1

16

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.

Community
  • 1
  • 1
DRH
  • 7,868
  • 35
  • 42
  • I think another process getting that port in meanwhile would be rare. So I would go with it. Anyway I was expecting a better way to ask the os instead of creating a dummy socket and closing it. – balki Dec 22 '11 at 09:16
  • 8
    For the record, here's the implementation of that suggestion: https://gist.github.com/3979133 – Danilo Bargen Oct 30 '12 at 09:02