system.py 363 B

123456789101112131415
  1. import socket
  2. def find_available_tcp_port() -> int:
  3. """Find an available TCP port, return -1 if none available.
  4. """
  5. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  6. try:
  7. sock.bind(('localhost', 0))
  8. port = sock.getsockname()[1]
  9. return port
  10. except Exception:
  11. return -1
  12. finally:
  13. sock.close()