Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Last active December 16, 2021 09:37
Show Gist options
  • Save wonderbeyond/a4441f40e4672bf2d1b730631960869f to your computer and use it in GitHub Desktop.
Save wonderbeyond/a4441f40e4672bf2d1b730631960869f to your computer and use it in GitHub Desktop.
Get random available port
"""
https://stackoverflow.com/questions/1075399/how-to-bind-to-any-available-port
https://eklitzke.org/binding-on-port-zero
"""
import socket
def get_available_port(host='localhost'):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, 0))
return sock.getsockname()[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment