Created
October 31, 2015 18:30
-
-
Save gabrielfalcao/20e567e188f588b65ba2 to your computer and use it in GitHub Desktop.
Getting a random free tcp port in python using sockets
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
# Getting a random free tcp port in python using sockets | |
def get_free_tcp_port(): | |
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
tcp.bind(('', 0)) | |
addr, port = tcp.getsockname() | |
tcp.close() | |
return port | |
def get_free_tcp_address(): | |
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
tcp.bind(('', 0)) | |
host, port = tcp.getsockname() | |
tcp.close() | |
return 'tcp://{host}:{port}'.format(**locals()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
more modern and pythonic: