Best-effort local IP and subnet detection without requiring root.
()
| 185 | # NETWORK HELPERS |
| 186 | # ───────────────────────────────────────────── |
| 187 | def run_command(cmd, timeout=10): |
| 188 | try: |
| 189 | result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) |
| 190 | if result.returncode == 0: |
| 191 | return result.stdout |
| 192 | except Exception: |
| 193 | return "" |
| 194 | return "" |
| 195 | |
| 196 | |
| 197 | |
| 198 | def get_local_subnet(): |
| 199 | """Best-effort local IP and subnet detection without requiring root.""" |
| 200 | # Method 1: UDP socket route trick |
| 201 | try: |
| 202 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 203 | sock.connect(("1.1.1.1", 80)) |
| 204 | local_ip = sock.getsockname()[0] |
| 205 | sock.close() |
| 206 | subnet = local_ip.rsplit(".", 1)[0] + ".0/24" |
| 207 | success(f"Local IP detected → {local_ip}") |
| 208 | return subnet, local_ip |
| 209 | except Exception: |
| 210 | pass |
| 211 | |
| 212 | # Method 2: ip route |
| 213 | route = run_command(["ip", "-4", "route"]) |
| 214 | if route: |
| 215 | src_match = re.search(r"src\s+(\d+\.\d+\.\d+\.\d+)", route) |
| 216 | cidr_match = re.search(r"(\d+\.\d+\.\d+\.\d+/\d+)", route) |
| 217 | local_ip = src_match.group(1) if src_match else None |
| 218 | subnet = cidr_match.group(1) if cidr_match else None |
| 219 | if local_ip and subnet: |
| 220 | success(f"Local IP detected via ip route → {local_ip}") |
| 221 | return subnet, local_ip |
| 222 | if local_ip: |
| 223 | subnet = local_ip.rsplit(".", 1)[0] + ".0/24" |
| 224 | success(f"Local IP detected via ip route → {local_ip}") |
| 225 | return subnet, local_ip |
| 226 | |
| 227 | # Method 3: ifconfig |
| 228 | output = run_command(["ifconfig"]) |
| 229 | if output: |
| 230 | match = re.search(r"inet\s(?:addr:)?(\d+\.\d+\.\d+\.\d+)", output) |
no test coverage detected