Get a port that's available for the given host and port range
(host: str, port_min: int = 8000, port_max: int = 9000)
| 49 | |
| 50 | |
| 51 | def find_available_port(host: str, port_min: int = 8000, port_max: int = 9000) -> int: |
| 52 | """Get a port that's available for the given host and port range""" |
| 53 | for port in range(port_min, port_max): |
| 54 | with closing(socket.socket()) as sock: |
| 55 | try: |
| 56 | if sys.platform in ("linux", "darwin"): |
| 57 | # Fixes bug on Unix-like systems where every time you restart the |
| 58 | # server you'll get a different port on Linux. This cannot be set |
| 59 | # on Windows otherwise address will always be reused. |
| 60 | # Ref: https://stackoverflow.com/a/19247688/3159288 |
| 61 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 62 | sock.bind((host, port)) |
| 63 | except OSError: |
| 64 | pass |
| 65 | else: |
| 66 | return port |
| 67 | msg = f"Host {host!r} has no available port in range {port_max}-{port_max}" |
| 68 | raise RuntimeError(msg) |
| 69 | |
| 70 | |
| 71 | def all_implementations() -> Iterator[BackendType[Any]]: |
no outgoing calls