Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.
Python cybersecurityd3jsebpfedrelectronfastapifirewallfleet-managementlinuxlittle-snitch-alternativemacosnetwork-monitornetwork-securitypacket-captureprivacyreactrustself-hostedsiemwindows
identify: learn device names from mDNS instances, LLMNR, NBNS and DHCP
MoneyLisa0eb901c1f3d0
diff --git a/README.md b/README.mdindex 8c8991a..7600a91 100644--- a/README.md+++ b/README.md@@ -61,7 +61,7 @@ The entire interface is available in **English and French**: use the `EN / FR` t- **Alert suppression** — each alert has an "Ignore this type/host" action; suppression rules are persisted (`alert_suppressions` table), applied before alerts are emitted or logged, and survivable across restarts via `POST /alerts/ignore` / `DELETE /alerts/ignore` / `GET /alerts/ignore`.- **History** — per-minute per-host and per-process byte/packet aggregates are kept in SQLite (`host_history`, `process_history`) for the retention window, powering the per-application view and `GET /history/host/{ip}` / `GET /history/process/{name}`.- **Diagnostics** — `GET /diagnostics` returns a JSON snapshot of the runtime (capture state, geo DB status, interface, versions, paths) with no secrets; the Settings panel can export it or open the log directory (Electron).-- **LAN devices** are discovered passively from the system ARP table — no active broadcast scanning.+- **LAN devices** are discovered passively from the system ARP table — no active broadcast scanning. Device names are learned from what devices broadcast themselves: mDNS `*.local` (Apple/Linux), LLMNR & NetBIOS names (Windows), DHCP hostname options, plus the full offline IEEE OUI vendor table, and your gateway is auto-detected as the router.- See [docs/threat-model.md](docs/threat-model.md) for the full threat model.### Docker (Linux)@@ -203,7 +203,7 @@ Toute l'interface est disponible en **français et en anglais** : utilisez le s- **Suppression d'alertes** — chaque alerte offre « Ignorer ce type/cet hôte » ; les règles sont persistées (`alert_suppressions`), appliquées avant émission, et gérables via `POST /alerts/ignore`, `DELETE /alerts/ignore`, `GET /alerts/ignore`.- **Historique** — les agrégats octets/paquets par minute, par hôte et par processus sont conservés dans SQLite (`host_history`, `process_history`) sur la fenêtre de rétention, et alimentent la vue par application ainsi que `GET /history/host/{ip}` et `GET /history/process/{nom}`.- **Diagnostic** — `GET /diagnostics` renvoie un instantané JSON du runtime (état de capture, géo, interface, versions, chemins) sans secrets ; le panneau Réglages peut l'exporter ou ouvrir le dossier des logs (Electron).-- **Appareils LAN** découverts passivement via la table ARP système — aucun scan broadcast actif.+- **Appareils LAN** découverts passivement via la table ARP système — aucun scan broadcast actif. Les noms sont appris de ce que les appareils diffusent eux-mêmes : mDNS `*.local` (Apple/Linux), LLMNR et noms NetBIOS (Windows), option hostname DHCP, plus la table de fabricants IEEE OUI complète hors ligne ; votre passerelle est détectée automatiquement comme routeur.- Voir [docs/threat-model.md](docs/threat-model.md) pour le modèle de menace complet.### Docker (Linux)diff --git a/backend/api/main.py b/backend/api/main.pyindex fefb0a6..b55bd3a 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -257,13 +257,14 @@ def _gateway() -> Optional[str]:def _learn_lan_hostname(ip: str, name: str,touched_devices: dict) -> None:"""- EN: An mDNS "*.local" announcement named this LAN device — store the- hostname on the entry (stub or real) so the UI shows "iPhone-de-Lisa"- instead of a bare IP. Never overwrites an existing name.- FR: Une annonce mDNS « *.local » a nommé cet appareil LAN — stocker le- nom d'hôte sur l'entrée (stub ou réelle) pour que l'UI affiche- « iPhone-de-Lisa » au lieu d'une IP nue. N'écrase jamais un nom- existant.+ EN: A passive announcement (mDNS "*.local", LLMNR, NBNS) named this LAN+ device — store the hostname on the entry (stub or real) so the UI+ shows "iPhone-de-Lisa" instead of a bare IP. Never overwrites an+ existing name.+ FR: Une annonce passive (mDNS « *.local », LLMNR, NBNS) a nommé cet+ appareil LAN — stocker le nom d'hôte sur l'entrée (stub ou réelle)+ pour que l'UI affiche « iPhone-de-Lisa » au lieu d'une IP nue.+ N'écrase jamais un nom existant."""dev = _ensure_lan_device(ip)if dev.get("hostname"):@@ -274,6 +275,54 @@ def _learn_lan_hostname(ip: str, name: str,touched_devices[dev["id"]] = dev+def _devname(dns_name: str) -> Optional[str]:+ """+ EN: Extract a device display name from a DNS-style name:+ "iPhone-de-Lisa._device-info._tcp.local" → "iPhone-de-Lisa"+ "MacBook-Pro.local" → "MacBook-Pro"+ "DESKTOP-ABC" → "DESKTOP-ABC"+ FR: Extraire le nom d'affichage d'un appareil d'un nom DNS :+ « iPhone-de-Lisa._device-info._tcp.local » → « iPhone-de-Lisa »+ « MacBook-Pro.local » → « MacBook-Pro »+ « DESKTOP-ABC » → « DESKTOP-ABC »+ """+ n = dns_name.strip()+ if n.lower().endswith(".local"):+ n = n[:-len(".local")]+ if "._" in n: # EN: mDNS service instance+ n = n.split("._", 1)[0] # FR: instance de service mDNS+ return n.strip() or None+++# EN: DHCP-learned names waiting for their device: a client announces its+# hostname (option 12) with its MAC, possibly before we know the IP the+# server will assign. Keyed by MAC, applied when the device appears.+# FR: Noms appris via DHCP en attente de leur appareil : un client annonce+# son nom (option 12) avec sa MAC, parfois avant que l'IP assignée ne+# soit connue. Indexés par MAC, appliqués quand l'appareil apparaît.+_pending_mac_names: dict[str, str] = {}+++def _learn_dhcp_name(hostname: str, req_ip: Optional[str], mac: str,+ touched_devices: dict) -> None:+ """+ EN: A client DHCP message revealed "this MAC is called <hostname>".+ If we already know the device (by requested IP or MAC), name it;+ otherwise remember the MAC→name pair for the next discovery.+ FR: Un message DHCP client révèle « cette MAC s'appelle <hostname> ».+ Si l'appareil est déjà connu (par IP demandée ou MAC), on le nomme ;+ sinon on retient le couple MAC→nom pour la prochaine découverte.+ """+ if req_ip and is_private(req_ip):+ _learn_lan_hostname(req_ip, hostname, touched_devices)+ return+ for dev in lan_devices.values():+ if dev.get("mac") == mac:+ _learn_lan_hostname(dev["ip"], hostname, touched_devices)+ return+ _pending_mac_names[mac] = hostname++# ── Packet handling / Traitement des paquets ─────────────────────────────────def on_packet(pkt: Packet) -> None:@@ -379,13 +428,34 @@ def _process_batch(packets: list[Packet]) -> None:# les réponses mDNS visent le multicast 224.0.0.251, qui ne doit# jamais devenir un nœud mais porte les noms « *.local » utiles.if pkt.dns:- dns53 = [a for a in pkt.dns if not a[0].lower().endswith(".local")]+ dns53 = []+ for name, ip, _ttl in pkt.dns:+ low = name.lower()+ if ip == "":+ # EN: Name CLAIMED BY THE SENDER (mDNS service instance,+ # NBNS registration) — the device is pkt.src_ip.+ # FR: Nom REVENDIQUÉ PAR L'ÉMETTEUR (instance de service+ # mDNS, enregistrement NBNS) — l'appareil est+ # pkt.src_ip.+ dev = _devname(name)+ if dev and is_private(pkt.src_ip):+ _learn_lan_hostname(pkt.src_ip, dev, touched_devices)+ elif low.endswith(".local"):+ # EN: Explicit "x.local → ip" binding from an mDNS A/AAAA.+ # FR: Liaison explicite « x.local → ip » d'un A/AAAA mDNS.+ if is_private(ip):+ _learn_lan_hostname(ip, name[:-len(".local")],+ touched_devices)+ elif is_private(ip) and "." not in name:+ # EN: LLMNR "PC-NAME → ip" — Windows name claims.+ # FR: LLMNR « PC-NAME → ip » — revendications Windows.+ _learn_lan_hostname(ip, name, touched_devices)+ else:+ dns53.append((name, ip, _ttl))if dns53:learn_dns_answers(dns53)- for name, ip, _ttl in pkt.dns:- if name.lower().endswith(".local") and is_private(ip):- _learn_lan_hostname(ip, name[:-len(".local")],- touched_devices)+ if pkt.dhcp:+ _learn_dhcp_name(*pkt.dhcp, touched_devices)if remote_ip in _whitelisted_ips or _is_noise_ip(remote_ip):continue@@ -577,6 +647,14 @@ async def _handle_device(device: Device, is_new: bool) -> None:if not device.hostname and prev.get("hostname"):node["hostname"] = prev["hostname"]node["label"] = prev["hostname"]+ # EN: A DHCP-learned name waiting for this MAC — applies even when+ # the stub didn't exist yet.+ # FR: Un nom appris via DHCP en attente de cette MAC — s'applique+ # même quand le stub n'existait pas encore.+ pending = _pending_mac_names.pop(device.mac, None)+ if pending and not node["hostname"]:+ node["hostname"] = pending+ node["label"] = pendingelse:node["alerted"] = Falselan_devices[node["id"]] = nodediff --git a/backend/capture/parser.py b/backend/capture/parser.pyindex ff952a3..f6e143d 100644--- a/backend/capture/parser.py+++ b/backend/capture/parser.py@@ -79,6 +79,9 @@ class ParsedPacket:tcp_flags: int = 0dns: list[tuple[str, str, int]] = field(default_factory=list)sni: Optional[str] = None+ # EN: (hostname, requested_ip|None, mac) from a client DHCP message.+ # FR: (nom d'hôte, ip demandée|None, mac) d'un message DHCP client.+ dhcp: Optional[tuple] = Nonedef parse_frame(linktype: int, buf: bytes) -> Optional[ParsedPacket]:@@ -266,6 +269,7 @@ def _parse_transport(payload: bytes, proto: int, src: str, dst: str,return Nonesport, dport = struct.unpack("!HH", payload[:4])udp_payload = payload[8:]+ dhcp = Noneif sport == 53 or dport == 53:dns = parse_dns(udp_payload)elif sport == 5353 or dport == 5353:@@ -274,9 +278,26 @@ def _parse_transport(payload: bytes, proto: int, src: str, dst: str,# FR: mDNS — les appareils annoncent « <nom>.local → <ip> » ici ;# c'est ainsi qu'on apprend les noms sans jamais émettre.dns = parse_mdns(udp_payload)+ elif sport == 5355 or dport == 5355:+ # EN: LLMNR — Windows' name protocol; same wire format as DNS.+ # Responses carry "PC-NAME → ip" for the responding machine.+ # FR: LLMNR — protocole de nommage Windows ; même format fil que+ # DNS. Les réponses portent « PC-NAME → ip » du répondant.+ dns = parse_dns(udp_payload)+ elif sport == 137 or dport == 137:+ # EN: NetBIOS NS — classic Windows name claims/registrations.+ # FR: NetBIOS NS — déclarations d'enregistrement de nom Windows.+ dns = parse_nbns(udp_payload)+ elif sport in (67, 68) or dport in (67, 68):+ # EN: DHCP — every device tells its hostname (option 12) when+ # joining/renewing; mapped to the device via MAC/requested-IP.+ # FR: DHCP — chaque appareil donne son nom d'hôte (option 12) en+ # rejoignant/renouvelant ; mappé via MAC/IP demandée.+ dns = []+ dhcp = parse_dhcp(udp_payload)else:dns = []- return ParsedPacket(src, dst, "UDP", wire_len, sport, dport, 0, dns, None)+ return ParsedPacket(src, dst, "UDP", wire_len, sport, dport, 0, dns, None, dhcp)if proto in (IPPROTO_ICMP, IPPROTO_ICMPV6):return ParsedPacket(src, dst, "ICMP", wire_len)@@ -365,18 +386,27 @@ def parse_dns(payload: bytes) -> list[tuple[str, str, int]]:def parse_mdns(payload: bytes) -> list[tuple[str, str, int]]:"""- EN: Parse an mDNS message (UDP/5353). Same wire format as DNS, but device- A/AAAA records often live in the ADDITIONAL section — so we walk all- three record sections, not just answers, and we don't require the QR- bit (mDNS announcements and responses both carry records). Only- "*.local" names are returned, as (hostname, ip, ttl) — hostname with- the .local suffix stripped.+ EN: Parse an mDNS message (UDP/5353). Same wire format as DNS, but the+ useful records hide everywhere, so we walk all three record sections+ and don't require the QR bit:++ - A/AAAA "*.local → ip" records → (name.local, ip, ttl)+ - PTR/SRV records → (instance_or_host_name, "", 0)+ the ip is EMPTY on purpose: it marks "the SENDER of this packet+ claims this name" — main.py maps it to pkt.src_ip. An instance+ like "iPhone-de-Lisa._device-info._tcp.local" carries the device+ display name before the first "._".+FR: Analyser un message mDNS (UDP/5353). Même format fil que DNS, mais les- enregistrements A/AAAA des appareils vivent souvent dans la section- ADDITIONNELLE — on parcourt donc les trois sections, pas seulement- les réponses, et le bit QR n'est pas exigé (annonces et réponses- portent des enregistrements). Seuls les noms « *.local » sont- renvoyés, en (nom d'hôte, ip, ttl) — suffixe .local retiré.+ enregistrements utiles sont partout : on parcourt les trois sections+ et le bit QR n'est pas exigé :++ - A/AAAA « *.local → ip » → (nom.local, ip, ttl)+ - PTR/SRV → (nom_instance_ou_hôte, "", 0)+ l'ip est volontairement VIDE : elle marque « l'ÉMETTEUR de ce+ paquet revendique ce nom » — main.py le mappe sur pkt.src_ip.+ Une instance « iPhone-de-Lisa._device-info._tcp.local » porte le+ nom d'affichage de l'appareil avant le premier « ._ »."""try:if len(payload) < 12:@@ -398,21 +428,147 @@ def parse_mdns(payload: bytes) -> list[tuple[str, str, int]]:if rdata_off + rdlen > len(payload):breakrdata = payload[rdata_off:rdata_off + rdlen]- # EN: Keep the ".local" suffix — main.py uses it to tell mDNS- # device names apart from regular DNS answers.- # FR: Garder le suffixe « .local » — main.py s'en sert pour- # distinguer les noms d'appareils mDNS des réponses DNS normales.- if name.lower().endswith(".local"):- if rtype == 1 and rdlen == 4: # EN: A / FR: A- answers.append((name, socket.inet_ntop(socket.AF_INET, rdata), ttl))- elif rtype == 28 and rdlen == 16: # EN: AAAA / FR: AAAA- answers.append((name, socket.inet_ntop(socket.AF_INET6, rdata), ttl))+ if rtype == 1 and rdlen == 4 and name.lower().endswith(".local"):+ answers.append((name, socket.inet_ntop(socket.AF_INET, rdata), ttl))+ elif rtype == 28 and rdlen == 16 and name.lower().endswith(".local"):+ answers.append((name, socket.inet_ntop(socket.AF_INET6, rdata), ttl))+ elif rtype in (12, 33): # EN: PTR / SRV — target is a name+ target, _ = _dns_name(payload, rdata_off + (6 if rtype == 33 else 0))+ if target.lower().endswith(".local"):+ answers.append((target, "", 0))off = rdata_off + rdlenreturn answersexcept (IndexError, struct.error, ValueError):return []+def _nbns_name(buf: bytes, off: int) -> tuple[Optional[str], int]:+ """+ EN: Decode one NetBIOS-encoded name at `off`: a 0x20 length byte, then+ 32 bytes of "first-level encoding" (each nibble as 'A'..'P'), then a+ null root label. The decoded value is 15 name chars + 1 suffix byte.+ Returns (display_name, end_offset) or (None, off) if not a NB name.+ FR: Décoder un nom NetBIOS à `off` : octet de longueur 0x20, puis+ 32 octets d'« encodage de premier niveau » (chaque quartet en+ 'A'..'P'), puis un label racine nul. La valeur décodée est 15+ caractères de nom + 1 octet de suffixe.+ Renvoie (nom_affiché, offset_fin) ou (None, off) si pas un nom NB.+ """+ if off >= len(buf) or buf[off] != 0x20:+ return None, off+ enc = buf[off + 1:off + 33]+ if len(enc) < 32:+ return None, off+ try:+ raw = bytes(((enc[i] - 0x41) << 4) | (enc[i + 1] - 0x41)+ for i in range(0, 32, 2))+ except (TypeError, ValueError):+ return None, off+ name = raw[:15].rstrip(b" \x00").decode("ascii", errors="replace")+ end = off + 33+ while end < len(buf) and buf[end] != 0: # EN: skip scope suffix+ end += buf[end] + 1 # FR: sauter le suffixe de scope+ return name, min(end + 1, len(buf))+++def parse_nbns(payload: bytes) -> list[tuple[str, str, int]]:+ """+ EN: Parse a NetBIOS Name Service message (UDP/137). We learn names in+ two situations — both mean "the SENDER claims this name":+ - QR=0 with opcode 5 (registration) or 8 (refresh): the question+ section carries the sender's own name+ - QR=1 responses: answer/authority/additional RRs carry the+ responder's name (and its NB address in rdata)+ Returns (name, "", 0) tuples — empty ip = "claim by packet source".+ FR: Analyser un message NetBIOS Name Service (UDP/137). On apprend des+ noms dans deux cas — qui signifient tous deux « l'ÉMETTEUR revendique+ ce nom » :+ - QR=0 avec opcode 5 (enregistrement) ou 8 (rafraîchissement) : la+ section question porte le nom de l'émetteur+ - réponses QR=1 : les RR réponse/autorité/additionnels portent le+ nom du répondant (et son adresse NB dans rdata)+ Renvoie des tuples (nom, "", 0) — ip vide = « revendiqué par la+ source du paquet ».+ """+ try:+ if len(payload) < 12:+ return []+ _, flags, qd, an, ns, ar = struct.unpack("!HHHHHH", payload[:12])+ qr = flags & 0x8000+ opcode = (flags >> 11) & 0xF+ off = 12+ claimed = []+ if not qr and opcode in (5, 8): # EN: name registration / refresh+ for _ in range(min(qd, 4)): # FR: enregistrement / rafraîchissement+ name, off = _nbns_name(payload, off)+ if name is None:+ break+ claimed.append((name, "", 0))+ off += 4 # EN: qtype + qclass / FR: qtype + qclass+ elif qr: # EN: response / FR: réponse+ for _ in range(qd): # EN: skip questions / FR: sauter les questions+ _, off = _nbns_name(payload, off)+ off += 4+ for _ in range(min(an + ns + ar, 8)):+ name, off = _nbns_name(payload, off)+ if name is None or off + 10 > len(payload):+ break+ _rt, _rc, _ttl, rdlen = struct.unpack("!HHIH", payload[off:off + 10])+ claimed.append((name, "", 0))+ off += 10 + rdlen+ return claimed[:8]+ except (IndexError, struct.error, ValueError):+ return []+++def parse_dhcp(payload: bytes) -> Optional[tuple]:+ """+ EN: Parse a client DHCP/BOOTP message (UDP 67/68). Layout: fixed header+ (236 B, chaddr = client MAC at offset 28) + magic cookie 63 82 53 63+ + TLV options. We want option 12 (hostname — what the user named the+ device) and option 50 (requested IP — binds name→ip directly).+ Returns (hostname, requested_ip|None, mac) or None. Server→client+ replies (op=2) carry no hostname, so they're skipped.+ FR: Analyser un message DHCP/BOOTP client (UDP 67/68). Structure :+ en-tête fixe (236 o, chaddr = MAC client à l'offset 28) + cookie+ magique 63 82 53 63 + options TLV. On veut l'option 12 (nom d'hôte —+ ce que l'utilisateur a nommé) et l'option 50 (IP demandée — lie+ nom→ip directement). Renvoie (nom, ip_demandée|None, mac) ou None.+ Les réponses serveur→client (op=2) ne portent pas de nom d'hôte,+ elles sont ignorées.+ """+ try:+ if len(payload) < 240 or payload[0] != 1:+ return None # EN: BOOTREQUEST only+ hlen = min(payload[2], 6) # FR: BOOTREQUEST seul+ mac = ":".join(f"{b:02X}" for b in payload[28:28 + hlen])+ if payload[236:240] != b"\x63\x82\x53\x63": # EN: magic cookie+ return None # FR: cookie magique+ hostname = None+ req_ip = None+ off = 240+ while off < len(payload):+ tag = payload[off]+ off += 1+ if tag == 0: # EN: pad / FR: bourrage+ continue+ if tag == 255 or off >= len(payload): # EN: end / FR: fin+ break+ ln = payload[off]+ off += 1+ val = payload[off:off + ln]+ off += ln+ if tag == 12: # EN: hostname / FR: nom d'hôte+ hostname = val.decode("ascii", errors="replace").strip("\x00 ")+ elif tag == 50 and ln == 4: # EN: requested IP / FR: IP demandée+ req_ip = socket.inet_ntoa(val)+ if not hostname:+ return None+ return (hostname, req_ip, mac)+ except (IndexError, struct.error, ValueError):+ return None++# ── TLS SNI / SNI TLS ────────────────────────────────────────────────────────def parse_tls_sni(payload: bytes) -> Optional[str]:diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.pyindex 53527e0..84c26ab 100644--- a/backend/capture/sniffer.py+++ b/backend/capture/sniffer.py@@ -75,6 +75,11 @@ class Packet:tcp_flags: int = 0sni: Optional[str] = Nonedns: list = field(default_factory=list)+ # EN: (hostname, requested_ip|None, mac) learned from a client DHCP+ # message — names the device before mDNS/LLMNR ever do.+ # FR: (nom d'hôte, ip demandée|None, mac) appris d'un message DHCP+ # client — nomme l'appareil avant même mDNS/LLMNR.+ dhcp: Optional[tuple] = Nonedef get_local_ips() -> set[str]:@@ -253,6 +258,7 @@ class PacketSniffer:tcp_flags=parsed.tcp_flags,sni=parsed.sni,dns=parsed.dns,+ dhcp=parsed.dhcp,))def start(self) -> None:diff --git a/backend/tests/test_parser.py b/backend/tests/test_parser.pyindex 988c006..a332f3a 100644--- a/backend/tests/test_parser.py+++ b/backend/tests/test_parser.py@@ -16,7 +16,8 @@ import structfrom capture.parser import (DLT_EN10MB, DLT_LINUX_SLL, DLT_LINUX_SLL2, DLT_NULL, DLT_RAW,- parse_frame, parse_dns, parse_mdns, parse_tls_sni,+ parse_frame, parse_dns, parse_mdns, parse_nbns, parse_dhcp,+ parse_tls_sni,)ETH = DLT_EN10MB@@ -269,7 +270,11 @@ def test_mdns_additional_section():FR: Enregistrement A en ADDITIONNELLE sous une réponse PTR — le cas réelle plus courant."""res = parse_mdns(mdns_frame("MacBook-Pro", b"\xc0\xa8\x01\x2a", "additional"))- assert res == [("MacBook-Pro.local", "192.168.1.42", 120)]+ # EN: the PTR answer yields a sender-claimed name (empty ip) AND the+ # additional A record yields the explicit binding.+ # FR: la réponse PTR donne un nom revendiqué par l'émetteur (ip vide) ET+ # le A en additionnelle donne la liaison explicite.+ assert res == [("ptr.local", "", 0), ("MacBook-Pro.local", "192.168.1.42", 120)]def test_mdns_udp_5353_flows_through_parser():@@ -290,3 +295,65 @@ def test_mdns_udp_5353_flows_through_parser():def test_mdns_malformed():assert parse_mdns(b"\x00") == []assert parse_mdns(b"\x00" * 12) == []+++# ── Device-name protocols: mDNS PTR / NBNS / DHCP ────────────────────────────+# ── Protocoles de nommage : PTR mDNS / NBNS / DHCP ────────────────────────────++def mdns_ptr_frame(instance: str) -> bytes:+ """EN: mDNS with a PTR answer: _device-info._tcp.local → instance.+ FR: mDNS avec réponse PTR : _device-info._tcp.local → instance."""+ def w(n):+ return b"".join(bytes([len(x)]) + x.encode() for x in n.split(".")) + b"\x00"+ rdata = w(instance)+ rec = w("_device-info._tcp.local") + struct.pack("!HHIH", 12, 1, 120, len(rdata)) + rdata+ return struct.pack("!HHHHHH", 0, 0x8400, 0, 1, 0, 0) + rec+++def test_mdns_ptr_instance_name():+ res = parse_mdns(mdns_ptr_frame("iPhone-de-Lisa._device-info._tcp.local"))+ assert res == [("iPhone-de-Lisa._device-info._tcp.local", "", 0)]+++def nb_name_wire(name: str, suffix: int = 0x00) -> bytes:+ """EN: NetBIOS first-level encoding: 15-char padded name + suffix byte,+ each byte as two letters 'A'..'P'.+ FR: Encodage NetBIOS de premier niveau : nom sur 15 caractères + octet+ de suffixe, chaque octet en deux lettres 'A'..'P'."""+ raw = name.encode().ljust(15, b" ")[:15] + bytes([suffix])+ enc = b"".join(bytes([0x41 + (b >> 4), 0x41 + (b & 15)]) for b in raw)+ return b"\x20" + enc + b"\x00"+++def test_nbns_registration():+ """EN: Name registration (QR=0, opcode 5) carries the sender's name.+ FR: L'enregistrement de nom (QR=0, opcode 5) porte le nom de l'émetteur."""+ q = nb_name_wire("PC-DE-LISA") + struct.pack("!HH", 0x20, 1)+ msg = struct.pack("!HHHHHH", 1, 5 << 11, 1, 0, 0, 0) + q+ assert parse_nbns(msg) == [("PC-DE-LISA", "", 0)]+++def dhcp_request(hostname: str, req_ip: bytes, mac: bytes) -> bytes:+ """EN: Minimal BOOTP REQUEST: 236B header + cookie + options 12/50/end.+ FR: BOOTP REQUEST minimal : en-tête 236 o + cookie + options 12/50/fin."""+ hdr = struct.pack("!BBBBIHH", 1, 1, 6, 0, 0x1234, 0, 0x8000)+ hdr += b"\x00" * 4 * 4 # ciaddr/yiaddr/siaddr/giaddr+ hdr += mac + b"\x00" * (16 - len(mac)) # chaddr+ hdr += b"\x00" * (64 + 128) # sname + file+ opts = bytes([12, len(hostname)]) + hostname.encode()+ opts += bytes([50, 4]) + req_ip+ return hdr + b"\x63\x82\x53\x63" + opts + b"\xff"+++def test_dhcp_hostname():+ res = parse_dhcp(dhcp_request("DESKTOP-ABC", b"\xc0\xa8\x01\xc6",+ b"\x58\xa0\x23\xe9\xe3\xb4"))+ assert res == ("DESKTOP-ABC", "192.168.1.198", "58:A0:23:E9:E3:B4")+++def test_dhcp_server_reply_ignored():+ """EN: op=2 (server reply) returns None — no hostname to learn.+ FR: op=2 (réponse serveur) renvoie None — pas de nom à apprendre."""+ reply = bytearray(dhcp_request("X", b"\x0a\x00\x00\x01", b"\x01" * 6))+ reply[0] = 2+ assert parse_dhcp(bytes(reply)) is None