Do not bind to a specific port. Instead, bind to port 0:
sock.bind(('', 0))
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
.
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()[1]
Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname()
right after bind()
.
If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:
import socketserver
with socketserver.TCPServer(("localhost", 0), None) as s:
free_port = s.server_address[1]
Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With