Fix Python – On localhost, how do I pick a free port number?

Question

Asked By – Anton L.

I’m trying to play with inter-process communication and since I could not figure out how to use named pipes under Windows I thought I’ll use network sockets. Everything happens locally. The server is able to launch slaves in a separate process and listens on some port. The slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21?

I’m using Python, if that cuts the choices down.

Now we will see solution for issue: On localhost, how do I pick a free port number?


Answer

Do not bind to a specific port. Instead, bind to port 0:

import socket
sock = socket.socket()
sock.bind(('', 0))
sock.getsockname()[1]

The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1], and pass it on to the slaves so that they can connect back.

sock is the socket that you created, returned by socket.socket.

This question is answered By – mark4o

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0