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

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.

Leave a Comment