Created
May 30, 2014 17:56
-
-
Save vodik/cc1d796b56795f02e8e3 to your computer and use it in GitHub Desktop.
next_free_port
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
def next_free_port(host, family, proto): | |
for res in socket.getaddrinfo(host, '0', family, proto): | |
(family, socktype, proto, _, sockaddr) = res | |
with socket.socket(family, socktype) as sock: | |
sock.bind((sockaddr[0], 0)) | |
return sock.getsockname()[:2] | |
print(next_free_port('vodik', socket.AF_INET, socket.SOCK_STREAM)) | |
print(next_free_port('vodik', socket.AF_INET, socket.SOCK_DGRAM)) | |
print(next_free_port('vodik', socket.AF_INET6, socket.SOCK_STREAM)) | |
print(next_free_port('vodik', socket.AF_INET6, socket.SOCK_DGRAM)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment