"""Read the comitup network state file written by the host.""" from __future__ import annotations import json import socket from pathlib import Path UNKNOWN = {"state": "UNKNOWN", "ssid": None, "ip": None} def _detect_ip() -> str | None: # UDP connect trick: picks the source address of the default route, no traffic sent. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect(("8.8.8.8", 53)) return str(sock.getsockname()[0]) except OSError: return None finally: sock.close() def read_network(path: str) -> dict: try: raw = json.loads(Path(path).read_text()) except (OSError, ValueError): result = dict(UNKNOWN) result["ip"] = _detect_ip() return result if not isinstance(raw, dict): result = dict(UNKNOWN) result["ip"] = _detect_ip() return result return { "state": str(raw.get("state") or "UNKNOWN"), "ssid": raw.get("ssid") or None, "ip": raw.get("ip") or None, "updated_at": raw.get("updated_at"), }