system.py 358 B

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