network_scanner icon indicating copy to clipboard operation
network_scanner copied to clipboard

The fab21 patch 1

Open TheFab21 opened this issue 2 months ago • 0 comments

Speed up discovery and keep hostnames (post-resolution) Summary

This PR makes network_scanner much faster on Docker/Synology setups while still exposing hostnames. Key idea: perform a fast, DNS-free discovery with Nmap, then do a targeted reverse-DNS only for active hosts, with a very short timeout. It also normalizes hostnames to the short label (e.g., Tuya_plug.santoni.ch → tuya_plug).

Motivation

Using Nmap with DNS resolution (-R or default reverse lookups) can introduce ~seconds of delay per IP on bridged Docker networks (PTR timeouts via the embedded resolver).

Disabling DNS with -n is fast but loses hostnames.

We want both: speed and useful hostnames.

What changed (from the original file)

Fast scan arguments

From: -sn

To: -sn -n -T4 Reason: discovery without DNS (-n) and with more aggressive timing (-T4) is dramatically faster, especially inside containers.

Post-scan reverse-DNS with short timeout

After Nmap returns active hosts, we attempt socket.gethostbyaddr(ip) only for hosts that lack a name from Nmap, using a very small timeout (e.g., 300 ms) to avoid global slowdowns.

Hostname normalization

New helper to convert any hostname to a “short label”: trim trailing dot, take the part before the first dot, lowercase it, and strip non [a-z0-9_-].

Example: Tuya_plug.santoni.ch → tuya_plug.

Robust extraction of names from Nmap output

Prefer nm[host].hostname(), but also check the hostnames list if present.

Safety & cleanliness

Restore the original default socket timeout after each reverse-DNS attempt so we don’t affect Home Assistant internals.

Keep vendor detection and MAC mapping behavior unchanged.

Preserve sorting by IP as before.

Implementation highlights

New utilities:

_short_label(name: str) -> str | None

_fast_rdns(ip: str, timeout: float = 0.3) -> str | None

Scan flow:

self.nm.scan(hosts=self.ip_range, arguments='-sn -n -T4')

For each active host:

read IP/MAC/vendor

get raw hostname from Nmap (and/or hostnames list)

normalize with _short_label

if empty, try _fast_rdns(ip); normalize that result too

Backwards compatibility

Entity name, attributes, and structure remain the same (devices list with ip, mac, name, type, vendor, hostname).

Only behavioral change is faster scans and more consistent short hostnames.

Performance impact

Eliminates per-IP PTR delays during discovery.

Reverse-DNS is done only for discovered hosts and with a tiny timeout → bounded, predictable latency even on /24 networks.

Testing

Docker + Synology (bridge): verified that a /24 scan completes quickly and hostnames appear where PTR exists or via Nmap’s own results.

Verified hostname normalization on FQDNs (.local, domain FQDNs, trailing dot).

Ensured default socket timeout is restored after each lookup.

TheFab21 avatar Oct 16 '25 15:10 TheFab21