Extract interface checks in unicast sweep into checkAddr()

Moves the IPv4/internal/link-local/prefix-size checks out of
localSubnetHosts() into a helper. No behaviour change: the 30 discovery
tests pass and onvif.ts stays at 100% coverage.
This commit is contained in:
Michael Mainguy 2026-09-19 12:07:59 -05:00
parent 5d181f3b3b
commit 18a19fdf81

View File

@ -45,6 +45,7 @@ const WS_DISCOVERY_PORT = 3702;
const MIN_SWEEP_PREFIX = 20;
const SWEEP_BATCH_SIZE = 64;
const SWEEP_BATCH_DELAY_MS = 15;
const CONTINUE_NO_PREFIX: {shouldContinue: boolean, prefix: number} = {shouldContinue: true, prefix: 0};
// Discovery is an EventEmitter singleton that emits "error" for malformed replies;
// without a listener Node would throw and take down the server process.
@ -119,14 +120,9 @@ function localSubnetHosts(): string[] {
const hosts = new Set<string>();
for (const addrs of Object.values(os.networkInterfaces())) {
for (const addr of addrs ?? []) {
if (addr.family !== "IPv4" || addr.internal || !addr.cidr) continue;
if (addr.address.startsWith("169.254.")) continue;
const prefix = Number(addr.cidr.split("/")[1]);
if (prefix < MIN_SWEEP_PREFIX || prefix > 30) {
console.warn(`[onvif] skipping unicast sweep of ${addr.cidr}`);
continue;
}
const mask = (0xffffffff << (32 - prefix)) >>> 0;
const checkResult = checkAddr(addr);
if (checkResult.shouldContinue) continue;
const mask = (0xffffffff << (32 - checkResult.prefix)) >>> 0;
const network = (ipToInt(addr.address) & mask) >>> 0;
const broadcast = (network | ~mask) >>> 0;
for (let n = network + 1; n < broadcast; n++) {
@ -137,6 +133,18 @@ function localSubnetHosts(): string[] {
}
return [...hosts];
}
function checkAddr(addr: os.NetworkInterfaceInfo): {shouldContinue: boolean, prefix: number} {
if (addr.family !== "IPv4" || addr.internal || !addr.cidr) return CONTINUE_NO_PREFIX;
if (addr.address.startsWith("169.254.")) return CONTINUE_NO_PREFIX;
const prefix = Number(addr.cidr.split("/")[1]);
if (prefix < MIN_SWEEP_PREFIX || prefix > 30) {
console.warn(`[onvif] skipping unicast sweep of ${addr.cidr}`);
return CONTINUE_NO_PREFIX;
}
return {shouldContinue: false, prefix: prefix};
}
function probeMessage(messageId: string): Buffer {
return Buffer.from(