Skip to content

Instantly share code, notes, and snippets.

@jkeyes
Created June 16, 2011 09:40
Show Gist options
  • Save jkeyes/1028958 to your computer and use it in GitHub Desktop.
Save jkeyes/1028958 to your computer and use it in GitHub Desktop.
Find unbound ports on localhost
import random
import socket
# range of ports where available ports can be found
PORT_RANGE = [33000,60000]
def find_unbound_port():
"""
Returns an unbound port number on 127.0.0.1.
"""
port = random.randint(*PORT_RANGE)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind(("127.0.0.1", port))
except socket.error:
port = get_port()
return port
if __name__ == "__main__":
print find_unbound_port()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment