Created
October 8, 2014 08:50
-
-
Save ergoithz/1d571fa7972752679815 to your computer and use it in GitHub Desktop.
Python port chooser
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 socket | |
used_ports = [None] | |
def choose_port(address='127.0.0.1'): | |
port = None | |
while port in used_ports: | |
testsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
testsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
testsocket.bind((address, 0)) | |
port = testsocket.getsockname()[1] | |
# testsocket.shutdown(socket.SHUT_RDWR) # seems to be unnecessary | |
testsocket.close() | |
used_ports.append(port) | |
return port |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment