On localhost, how do I pick a free port number?
For the sake of snippet of what the guys have explained above:
import socket from contextlib import closing def find_free_port(): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: s.bind(('', 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s.getsockname()
Do not bind to a specific port. Instead, bind to port 0:
import socket sock = socket.socket() sock.bind(('', 0)) sock.getsockname()
The OS will then pick an available port for you. You can get the port that was chosen using
sock.getsockname(), and pass it on to the slaves so that they can connect back.
sock is the socket that you created, returned by