Created
December 28, 2013 02:55
-
-
Save thepaul/8155625 to your computer and use it in GitHub Desktop.
choose a port number unused for TCP on all local inet interfaces (or on a particular interface). use sock_type=socket.SOCK_DGRAM for an unused UDP port instead of TCP.
This file contains hidden or 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 | |
import contextlib | |
def choose_unused_port(interface='0.0.0.0', sock_type=socket.SOCK_STREAM): | |
with contextlib.closing(socket.socket(socket.AF_INET, sock_type)) as s: | |
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
s.bind((interface, 0)) | |
return s.getsockname()[1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment