ports.py 836 B

123456789101112131415161718192021222324252627282930
  1. import random
  2. import socket
  3. ATTEMPTS = 25
  4. # range 10000-10199 is reserved for Skynet on Sandbox machines
  5. MIN_PORT = 10200
  6. MAX_PORT = 25000
  7. def is_port_open(host, port):
  8. _socket = socket.socket(socket.AF_INET)
  9. return _socket.connect_ex((host, port)) != 0
  10. def find_free_port(range_start=MIN_PORT, range_end=MAX_PORT, attempts=ATTEMPTS):
  11. """
  12. Finds free port
  13. :param range_start: start of range
  14. :param range_end: end of range
  15. :param attempts: number of tries to find free port
  16. :return: some open port in a given range
  17. """
  18. ports = [random.randint(range_start, range_end) for _ in range(attempts)]
  19. while ports:
  20. port = ports.pop()
  21. if is_port_open('', port):
  22. return port
  23. raise RuntimeError('Could not find free port in range = ' + str((range_start, range_end)))