Skip to content

Instantly share code, notes, and snippets.

@algal
Created October 20, 2024 02:09
Show Gist options
  • Save algal/c7692b34efed9a4ba7de37177bc8248f to your computer and use it in GitHub Desktop.
Save algal/c7692b34efed9a4ba7de37177bc8248f to your computer and use it in GitHub Desktop.
def find_free_port(candidates=[]):
for p in (candidates + [0]):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(('localhost',p))
return s.getsockname()[1]
except Exception:
logging.info(f"Could not bind to port {p}. Trying another")
port = find_free_port([5001,5010,5100])
print(f"Free port: {port}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment