Picking an unused port is easy to do using the socket module.
1 2 3 4 5 6 7 8 | import socket
def PickUnusedPort():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 0))
addr, port = s.getsockname()
s.close()
return port
|
Tags: network
port is not guaranteed to be free. I have been using similar code for a while and it is very useful. How ever, for the sake of completeness, you should point out that there is small window where port can be taken by some other process. - Raghu