Skip to content

network

dev_tool.tools.network

log = logging.getLogger(__name__) module-attribute

get_local_ip

A function that gets the local IP address of the machine.

On Linux/WSL, returns '0.0.0.0' to allow external access.

Returns:

  • str

    The local IP address, or '127.0.0.1' if it cannot be determined.

Source code in dev_tool/tools/network.py
def get_local_ip() -> str:
    """
    A function that gets the local IP address of the machine.

    On Linux/WSL, returns '0.0.0.0' to allow external access.

    :return: The local IP address, or '127.0.0.1' if it cannot be determined.
    """

    if sys.platform != OperatingSystem.WINDOWS:
        return '0.0.0.0'  # noqa: S104

    try:
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as handle:
            connection = ('8.8.8.8', 80)
            handle.connect(connection)
            ip, _ = handle.getsockname()

            return ip
    except Exception:
        return '127.0.0.1'

is_port_ready

A function that waits for a port to accept connections.

Parameters:

  • host (str) –

    The host address to check.

  • port (int) –

    The port number to check.

  • timeout (float, default: 30.0 ) –

    The maximum time to wait in seconds.

Returns:

  • bool

    True if the port is ready, False if the timeout was reached.

Source code in dev_tool/tools/network.py
def is_port_ready(host: str, port: int, timeout: float = 30.0) -> bool:
    """
    A function that waits for a port to accept connections.

    :param host: The host address to check.
    :param port: The port number to check.
    :param timeout: The maximum time to wait in seconds.
    :return: True if the port is ready, False if the timeout was reached.
    """

    start = time.monotonic()

    while time.monotonic() - start < timeout:
        try:
            with socket.create_connection((host, port), timeout=1):
                return True
        except (ConnectionRefusedError, OSError):
            time.sleep(0.5)

    return False