Skip to content

Instantly share code, notes, and snippets.

@romanvm
Created January 5, 2020 07:26
Show Gist options
  • Save romanvm/2105d7bd82b52dbbf8e739855ceff50f to your computer and use it in GitHub Desktop.
Save romanvm/2105d7bd82b52dbbf8e739855ceff50f to your computer and use it in GitHub Desktop.
# coding: utf-8
from __future__ import print_function
import random
import socket
def get_random_port():
random.seed()
while True:
port = random.randint(4000, 16000)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind(('127.0.0.1', port))
except OSError:
continue
finally:
sock.close()
return port
if __name__ == '__main__':
print(get_random_port())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment