views:

235

answers:

2

I want to get any random open TCP port on localhost in Python. What is the easiest way?

+1  A: 

My current solution:

def get_open_port():
        import socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(("",0))
        s.listen(1)
        port = s.getsockname()[1]
        s.close()
        return port

Not very nice and also not 100% correct but it works for now.

Albert
A: 

I actually use the following in one of my programs:

port = random.randint(10000,60000)

Of course, this is even more prone to collisions than the code you have. But I've never had a problem with it. The point is, at any given time, most of those high-numbered ports are not in use and if you just pick one at random, having a conflict with another process is pretty unlikely. If you do something like the solution you posted in your answer (opening a socket and grabbing its port number), it's almost certain that the port isn't going to conflict. So if this is something that you'll only be using for yourself (as opposed to something you're going to release to the public), think about whether it's worth coming up with a truly bulletproof solution. Odds are it'll never make a difference.

Motivated by Marcelo Cantos' comment on your question, I will add that the standard solution in cases like this is to have the process that will be using the port bind to it and then share that information with any other program that needs it. Typically it'll do something like writing a temporary file containing the port number to some standard location in the filesystem. Since the process you're working with doesn't do that, in some sense whatever solution you come up with will be a bit of a hack. But again, if it's just for your own use, that's probably fine.

David Zaslavsky