| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
"""Utility function to check if a port is open.""" |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
import asyncio |
| 13 |
import socket |
| 14 |
from typing import TYPE_CHECKING |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
if TYPE_CHECKING: |
| 21 |
from httpx import URL |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
__all__ = ["port_check_url"] |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
async def port_check_url(url: URL, timeout: int = 5) -> bool: |
| 37 |
"""Open the port designated by the URL given the timeout in seconds. |
| 38 |
|
| 39 |
Parameters |
| 40 |
---------- |
| 41 |
url |
| 42 |
The URL that provides the target system. |
| 43 |
timeout |
| 44 |
Time to await for the port to open in seconds. |
| 45 |
|
| 46 |
Returns |
| 47 |
------- |
| 48 |
bool |
| 49 |
If the port is available then return True; False otherwise. |
| 50 |
""" |
| 51 |
port = url.port or socket.getservbyname(url.scheme) |
| 52 |
|
| 53 |
try: |
| 54 |
wr: asyncio.StreamWriter |
| 55 |
_, wr = await asyncio.wait_for(asyncio.open_connection(host=url.host, port=port), timeout=timeout) |
| 56 |
|
| 57 |
|
| 58 |
wr.close() |
| 59 |
|
| 60 |
except TimeoutError: |
| 61 |
return False |
| 62 |
return True |