Created
June 16, 2011 09:40
-
-
Save jkeyes/1028958 to your computer and use it in GitHub Desktop.
Find unbound ports on localhost
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
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