Last active
December 16, 2021 09:37
-
-
Save wonderbeyond/a4441f40e4672bf2d1b730631960869f to your computer and use it in GitHub Desktop.
Get random available port
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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