Skip to content

Instantly share code, notes, and snippets.

@bebosudo
Created March 6, 2019 14:44
Show Gist options
  • Save bebosudo/b166e4c618db94fc9020c9e76e1ea7df to your computer and use it in GitHub Desktop.
Save bebosudo/b166e4c618db94fc9020c9e76e1ea7df to your computer and use it in GitHub Desktop.
Search for a free TCP port in python 3 (not completely safe, since between the check and the usage, there could be a race-condition)
#!/usr/bin/env python3
import socket
def search_free_port():
port = 5000
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(('localhost', port)) != 0:
return port
port += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment