Skip to content

Instantly share code, notes, and snippets.

@ergoithz
Created October 8, 2014 08:50
Show Gist options
  • Save ergoithz/1d571fa7972752679815 to your computer and use it in GitHub Desktop.
Save ergoithz/1d571fa7972752679815 to your computer and use it in GitHub Desktop.
Python port chooser
import socket
used_ports = [None]
def choose_port(address='127.0.0.1'):
port = None
while port in used_ports:
testsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
testsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
testsocket.bind((address, 0))
port = testsocket.getsockname()[1]
# testsocket.shutdown(socket.SHUT_RDWR) # seems to be unnecessary
testsocket.close()
used_ports.append(port)
return port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment