Skip to content

Instantly share code, notes, and snippets.

@drhirsch
Forked from dbrgn/gist:3979133
Last active December 30, 2015 18:04
Show Gist options
  • Save drhirsch/4e91b7548d63885d4774 to your computer and use it in GitHub Desktop.
Save drhirsch/4e91b7548d63885d4774 to your computer and use it in GitHub Desktop.
Find an available port from Python script
#!/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