I want to get any random open TCP port on localhost in Python. What is the easiest way?
The free port can be found by binding a socket to a port selected by the operating system. After the operating system selects a port the socket can be disposed. However, this solution is not resistant to race conditions - in the short time between getting the free port number and using this port other process may use this port.
def find_free_port():
s = socket.socket()
s.bind(('', 0)) # Bind to a free port provided by the host.
return s.getsockname()[1] # Return the port number assigned.