repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ui/network.ts
RawFile outline
import { type NetworkInterfaceInfo, networkInterfaces } from "node:os";
export type InterfaceMap = Record<string, NetworkInterfaceInfo[] | undefined>;
export function chooseLanAddress(
interfaces: InterfaceMap = networkInterfaces(),
): string {
const candidates = Object.values(interfaces)
.flatMap((items) => items ?? [])
.filter((item) => item.family === "IPv4" && !item.internal)
.map((item) => item.address)
.sort((a, b) => scoreAddress(b) - scoreAddress(a));
return candidates[0] ?? "127.0.0.1";
}
export function listenHostFor(address: string): string {
return address === "127.0.0.1" ? "127.0.0.1" : "0.0.0.0";
}
export function uiUrl(address: string, port: number, token: string): string {
return `http://${address}:${port}/?token=${encodeURIComponent(token)}`;
}
function scoreAddress(address: string): number {
if (address.startsWith("192.168.")) return 30;
if (address.startsWith("10.")) return 20;
if (/^172\.(1[6-9]|2\d|3[01])\./.test(address)) return 10;
return 1;
}