-
-
Save drhirsch/4e91b7548d63885d4774 to your computer and use it in GitHub Desktop.
Find an available port from Python script
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
#!/usr/bin/env python3 | |
""" for use from shell, returns on STDOUT a free port number. | |
Yes, there is a slight race condition where between end of this program and start of your shell program, | |
another program could grab this port. | |
Useful for scripts with SSH port forwarding for example, where you have one or more hops before the final host. | |
reference: http://stackoverflow.com/questions/1365265/on-localhost-how-to-pick-a-free-port-number | |
Michael Hirsch | |
""" | |
from socket import socket | |
s = socket() | |
s.bind(('',0)) | |
print(s.getsockname()[1]) #stdout | |
s.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment