psnet 1.0.0

A beautiful real-time TUI network monitor for Windows — 9 tabs, GeoIP, device discovery, firewall, topology & more
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
//! Deep network probing — 10 parallel discovery methods for maximum host coverage.
//!
//! Methods:
//!   1. ARP (SendARP)              — Layer 2 neighbor resolution
//!   2. ARP Cache (GetIpNetTable)  — Read OS neighbor table (zero traffic)
//!   3. ICMP Ping (IcmpSendEcho)   — Layer 3 echo (crosses VPN tunnels!)
//!   4. TCP Connect Probe          — Layer 4 port probe (80,443,445,22,3389,8080,135,139,53)
//!   5. NetBIOS NBSTAT (UDP 137)   — Windows/Samba name resolution per-host
//!   6. mDNS (UDP 5353)            — Multicast DNS discovery (Apple, IoT, Linux)
//!   7. SSDP/UPnP (UDP 1900)      — Universal Plug and Play device discovery
//!   8. DNS PTR Reverse Lookup     — getnameinfo() reverse DNS per-host
//!   9. LLMNR (UDP 5355)           — Link-Local Multicast Name Resolution
//!  10. NetBIOS Broadcast (UDP 137)— Subnet-wide NetBIOS name broadcast

use std::collections::{HashMap, HashSet};
use std::net::{Ipv4Addr, SocketAddrV4, TcpStream, UdpSocket};
use std::sync::Mutex;
use std::thread;
use std::time::Duration;

// ─── Win32 FFI ──────────────────────────────────────────────────────────────

#[link(name = "iphlpapi")]
extern "system" {
    fn SendARP(DestIP: u32, SrcIP: u32, pMacAddr: *mut u8, PhyAddrLen: *mut u32) -> u32;
    fn GetIpNetTable(pIpNetTable: *mut u8, pdwSize: *mut u32, bOrder: i32) -> u32;
    fn IcmpCreateFile() -> isize;
    fn IcmpCloseHandle(IcmpHandle: isize) -> i32;
    fn IcmpSendEcho(
        IcmpHandle: isize,
        DestinationAddress: u32,
        RequestData: *const u8,
        RequestSize: u16,
        RequestOptions: *const u8,
        ReplyBuffer: *mut u8,
        ReplySize: u32,
        Timeout: u32,
    ) -> u32;
}

#[repr(C)]
#[allow(non_snake_case)]
struct SOCKADDR_IN {
    sin_family: i16,
    sin_port: u16,
    sin_addr: u32, // network byte order
    sin_zero: [u8; 8],
}

#[link(name = "ws2_32")]
extern "system" {
    fn getnameinfo(
        sa: *const SOCKADDR_IN,
        salen: i32,
        host: *mut u8,
        hostlen: u32,
        serv: *mut u8,
        servlen: u32,
        flags: i32,
    ) -> i32;
}

const INVALID_HANDLE_VALUE: isize = -1;
const ERROR_BUFFER_OVERFLOW: u32 = 111;
const ERROR_SUCCESS: u32 = 0;
const AF_INET: i16 = 2;
const NI_NAMEREQD: i32 = 8;

// ─── Result types ───────────────────────────────────────────────────────────

/// A single probe hit from one discovery method.
pub(crate) struct ProbeHit {
    pub(crate) ip: Ipv4Addr,
    pub(crate) mac: Option<String>,
    pub(crate) hostname: Option<String>,
    pub(crate) method: &'static str,
}

/// Merged host after deduplication across all methods.
pub struct MergedHost {
    pub ip: Ipv4Addr,
    pub mac: Option<String>,
    pub hostname: Option<String>,
    pub methods: Vec<&'static str>,
}

// ─── Main entry point ───────────────────────────────────────────────────────

/// Run ALL 10 probe methods in parallel against a subnet.
/// Returns deduplicated hosts with merged info from every method that found them.
pub fn deep_scan_subnet(
    local_ip: Ipv4Addr,
    mask: Ipv4Addr,
    _gateway: Option<Ipv4Addr>,
) -> Vec<MergedHost> {
    let targets = super::subnet_ips(local_ip, mask);
    if targets.is_empty() {
        return Vec::new();
    }

    let hits: Mutex<Vec<ProbeHit>> = Mutex::new(Vec::new());

    thread::scope(|s| {
        // 1. ARP scan — Layer 2
        {
            let h = &hits;
            let t = &targets;
            s.spawn(move || {
                let r = arp_scan(t, local_ip);
                h.lock().unwrap().extend(r);
            });
        }
        // 2. ARP cache — GetIpNetTable (zero traffic, instant)
        {
            let h = &hits;
            let t = &targets;
            s.spawn(move || {
                let r = arp_cache_read(t);
                h.lock().unwrap().extend(r);
            });
        }
        // 3. ICMP ping sweep — crosses L3 tunnels (VPN!)
        {
            let h = &hits;
            let t = &targets;
            s.spawn(move || {
                let r = icmp_ping_sweep(t);
                h.lock().unwrap().extend(r);
            });
        }
        // 4. TCP connect probe — finds hosts with open services
        {
            let h = &hits;
            let t = &targets;
            s.spawn(move || {
                let r = tcp_connect_probe(t);
                h.lock().unwrap().extend(r);
            });
        }
        // 5. NetBIOS NBSTAT — Windows/Samba devices
        {
            let h = &hits;
            let t = &targets;
            s.spawn(move || {
                let r = netbios_scan(t);
                h.lock().unwrap().extend(r);
            });
        }
        // 6. mDNS multicast — Apple, Linux, IoT
        {
            let h = &hits;
            s.spawn(move || {
                let r = mdns_discover(local_ip);
                h.lock().unwrap().extend(r);
            });
        }
        // 7. SSDP/UPnP — routers, TVs, smart home
        {
            let h = &hits;
            s.spawn(move || {
                let r = ssdp_discover(local_ip);
                h.lock().unwrap().extend(r);
            });
        }
        // 8. DNS PTR reverse lookup
        {
            let h = &hits;
            let t = &targets;
            s.spawn(move || {
                let r = dns_reverse_scan(t);
                h.lock().unwrap().extend(r);
            });
        }
        // 9. LLMNR — Link-Local Multicast Name Resolution
        {
            let h = &hits;
            s.spawn(move || {
                let r = llmnr_discover(local_ip);
                h.lock().unwrap().extend(r);
            });
        }
        // 10. NetBIOS broadcast — subnet-wide name query
        {
            let h = &hits;
            s.spawn(move || {
                let r = nbt_broadcast(local_ip, mask);
                h.lock().unwrap().extend(r);
            });
        }
    });

    merge_hits(hits.into_inner().unwrap(), local_ip)
}

// ─── Merge / dedup ──────────────────────────────────────────────────────────

pub(crate) fn merge_hits(hits: Vec<ProbeHit>, local_ip: Ipv4Addr) -> Vec<MergedHost> {
    let mut map: HashMap<Ipv4Addr, MergedHost> = HashMap::new();

    for hit in hits {
        // Skip our own IP
        if hit.ip == local_ip {
            continue;
        }

        let entry = map.entry(hit.ip).or_insert_with(|| MergedHost {
            ip: hit.ip,
            mac: None,
            hostname: None,
            methods: Vec::new(),
        });

        // Prefer non-empty MACs
        if entry.mac.is_none() && hit.mac.is_some() {
            entry.mac = hit.mac;
        }

        // Prefer longer / more descriptive hostnames
        if let Some(h) = hit.hostname {
            if !h.is_empty() {
                let dominated = entry.hostname.as_ref()
                    .map(|existing| h.len() > existing.len())
                    .unwrap_or(true);
                if dominated {
                    entry.hostname = Some(h);
                }
            }
        }

        if !entry.methods.contains(&hit.method) {
            entry.methods.push(hit.method);
        }
    }

    let mut result: Vec<MergedHost> = map.into_values().collect();
    result.sort_by(|a, b| a.ip.cmp(&b.ip));
    result
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 1: ARP Scan (SendARP) — Layer 2
// ═════════════════════════════════════════════════════════════════════════════

pub(crate) fn arp_scan(targets: &[Ipv4Addr], local_ip: Ipv4Addr) -> Vec<ProbeHit> {
    let src = u32::from(local_ip).to_be();
    let hits: Mutex<Vec<ProbeHit>> = Mutex::new(Vec::new());

    for chunk in targets.chunks(64) {
        thread::scope(|s| {
            for &target in chunk {
                let h = &hits;
                s.spawn(move || {
                    let dest = u32::from(target).to_be();
                    let mut mac = [0u8; 6];
                    let mut len: u32 = 6;
                    let ret = unsafe { SendARP(dest, src, mac.as_mut_ptr(), &mut len) };
                    if ret == 0 && len >= 6 {
                        h.lock().unwrap().push(ProbeHit {
                            ip: target,
                            mac: Some(format_mac(&mac)),
                            hostname: None,
                            method: "ARP",
                        });
                    }
                });
            }
        });
    }

    hits.into_inner().unwrap()
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 2: ARP Cache (GetIpNetTable) — zero traffic, reads OS table
// ═════════════════════════════════════════════════════════════════════════════

#[repr(C)]
#[allow(non_snake_case)]
struct MIB_IPNETROW {
    dwIndex: u32,
    dwPhysAddrLen: u32,
    bPhysAddr: [u8; 8],
    dwAddr: u32,
    dwType: u32,
}

pub(crate) fn arp_cache_read(targets: &[Ipv4Addr]) -> Vec<ProbeHit> {
    let mut hits = Vec::new();
    let target_set: HashSet<Ipv4Addr> = targets.iter().copied().collect();

    unsafe {
        let mut size: u32 = 0;
        let ret = GetIpNetTable(std::ptr::null_mut(), &mut size, 0);
        if ret != ERROR_BUFFER_OVERFLOW || size == 0 {
            return hits;
        }

        let mut buf = vec![0u8; size as usize];
        let ret = GetIpNetTable(buf.as_mut_ptr(), &mut size, 0);
        if ret != ERROR_SUCCESS {
            return hits;
        }

        let num_entries = *(buf.as_ptr() as *const u32);
        let rows_ptr = buf.as_ptr().add(4) as *const MIB_IPNETROW;

        for i in 0..num_entries as usize {
            let row = &*rows_ptr.add(i);
            // 3=dynamic, 4=static; skip invalid(2) and other(1)
            if row.dwType < 3 {
                continue;
            }
            let ip = Ipv4Addr::from(u32::from_be(row.dwAddr));
            if !target_set.contains(&ip) {
                continue;
            }

            let mac = if row.dwPhysAddrLen >= 6 {
                Some(format_mac(&row.bPhysAddr[..6].try_into().unwrap()))
            } else {
                None
            };

            hits.push(ProbeHit {
                ip,
                mac,
                hostname: None,
                method: "ARP-Cache",
            });
        }
    }

    hits
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 3: ICMP Ping Sweep (IcmpSendEcho) — Layer 3, crosses VPN tunnels!
// ═════════════════════════════════════════════════════════════════════════════

pub(crate) fn icmp_ping_sweep(targets: &[Ipv4Addr]) -> Vec<ProbeHit> {
    let hits: Mutex<Vec<ProbeHit>> = Mutex::new(Vec::new());

    for chunk in targets.chunks(64) {
        thread::scope(|s| {
            for &target in chunk {
                let h = &hits;
                s.spawn(move || {
                    if icmp_ping_one(target) {
                        h.lock().unwrap().push(ProbeHit {
                            ip: target,
                            mac: None,
                            hostname: None,
                            method: "ICMP",
                        });
                    }
                });
            }
        });
    }

    hits.into_inner().unwrap()
}

fn icmp_ping_one(target: Ipv4Addr) -> bool {
    unsafe {
        let handle = IcmpCreateFile();
        if handle == INVALID_HANDLE_VALUE || handle == 0 {
            return false;
        }

        let data = b"psnt";
        // ICMP_ECHO_REPLY is 28 bytes + data; 64 bytes is plenty
        let mut reply_buf = [0u8; 64];
        let dest = u32::from(target).to_be();

        let ret = IcmpSendEcho(
            handle,
            dest,
            data.as_ptr(),
            data.len() as u16,
            std::ptr::null(),
            reply_buf.as_mut_ptr(),
            reply_buf.len() as u32,
            300, // 300ms timeout
        );

        IcmpCloseHandle(handle);
        ret > 0
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 4: TCP Connect Probe — finds hosts with listening services
// ═════════════════════════════════════════════════════════════════════════════

const TCP_PROBE_PORTS: &[u16] = &[80, 443, 445, 22, 3389, 8080, 135, 139, 53];

pub(crate) fn tcp_connect_probe(targets: &[Ipv4Addr]) -> Vec<ProbeHit> {
    let hits: Mutex<Vec<ProbeHit>> = Mutex::new(Vec::new());
    let found: Mutex<HashSet<Ipv4Addr>> = Mutex::new(HashSet::new());

    for chunk in targets.chunks(32) {
        thread::scope(|s| {
            for &target in chunk {
                let h = &hits;
                let f = &found;
                s.spawn(move || {
                    for &port in TCP_PROBE_PORTS {
                        let addr = SocketAddrV4::new(target, port);
                        if TcpStream::connect_timeout(
                            &std::net::SocketAddr::V4(addr),
                            Duration::from_millis(250),
                        )
                        .is_ok()
                        {
                            if f.lock().unwrap().insert(target) {
                                h.lock().unwrap().push(ProbeHit {
                                    ip: target,
                                    mac: None,
                                    hostname: None,
                                    method: "TCP",
                                });
                            }
                            break;
                        }
                    }
                });
            }
        });
    }

    hits.into_inner().unwrap()
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 5: NetBIOS NBSTAT Query (UDP 137) — per-host name resolution
// ═════════════════════════════════════════════════════════════════════════════

pub(crate) fn netbios_scan(targets: &[Ipv4Addr]) -> Vec<ProbeHit> {
    let hits: Mutex<Vec<ProbeHit>> = Mutex::new(Vec::new());
    let query = build_nbstat_query();

    for chunk in targets.chunks(32) {
        thread::scope(|s| {
            for &target in chunk {
                let h = &hits;
                let q = &query;
                s.spawn(move || {
                    if let Some(name) = netbios_query_one(target, q) {
                        h.lock().unwrap().push(ProbeHit {
                            ip: target,
                            mac: None,
                            hostname: Some(name),
                            method: "NetBIOS",
                        });
                    }
                });
            }
        });
    }

    hits.into_inner().unwrap()
}

fn build_nbstat_query() -> Vec<u8> {
    let mut pkt = Vec::with_capacity(50);
    // DNS-like header
    pkt.extend_from_slice(&[0x00, 0x01]); // Transaction ID
    pkt.extend_from_slice(&[0x00, 0x00]); // Flags: query
    pkt.extend_from_slice(&[0x00, 0x01]); // Questions: 1
    pkt.extend_from_slice(&[0x00, 0x00]); // Answers: 0
    pkt.extend_from_slice(&[0x00, 0x00]); // Authority: 0
    pkt.extend_from_slice(&[0x00, 0x00]); // Additional: 0
    // Name: "*" (wildcard) in NetBIOS first-level encoding
    // '*' = 0x2A -> 'C','K'; pad with 0x00 -> 'A','A' × 15
    pkt.push(0x20); // length = 32
    pkt.extend_from_slice(b"CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    pkt.push(0x00); // end of name
    pkt.extend_from_slice(&[0x00, 0x21]); // Type: NBSTAT
    pkt.extend_from_slice(&[0x00, 0x01]); // Class: IN
    pkt
}

fn netbios_query_one(target: Ipv4Addr, query: &[u8]) -> Option<String> {
    let sock = UdpSocket::bind("0.0.0.0:0").ok()?;
    sock.set_read_timeout(Some(Duration::from_millis(400))).ok()?;
    sock.send_to(query, SocketAddrV4::new(target, 137)).ok()?;

    let mut buf = [0u8; 512];
    let (len, _) = sock.recv_from(&mut buf).ok()?;
    parse_nbstat_response(&buf[..len])
}

fn parse_nbstat_response(data: &[u8]) -> Option<String> {
    if data.len() < 57 {
        return None;
    }
    let name_count = data[56] as usize;
    if name_count == 0 || data.len() < 57 + 18 {
        return None;
    }
    // First name entry: 15 bytes name + 1 byte suffix + 2 bytes flags
    let name_bytes = &data[57..57 + 15];
    let name = std::str::from_utf8(name_bytes).ok()?.trim().to_string();
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 6: mDNS Discovery (UDP 5353 multicast)
// ═════════════════════════════════════════════════════════════════════════════

pub(crate) fn mdns_discover(local_ip: Ipv4Addr) -> Vec<ProbeHit> {
    let mut hits = Vec::new();

    let sock = match UdpSocket::bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) {
        Ok(s) => s,
        Err(_) => return hits,
    };
    let _ = sock.set_read_timeout(Some(Duration::from_millis(2000)));
    let _ = sock.set_broadcast(true);

    // Join mDNS multicast group
    let _ = sock.join_multicast_v4(&Ipv4Addr::new(224, 0, 0, 251), &local_ip);

    // Query for service discovery PTR
    let query = build_mdns_services_query();
    let _ = sock.send_to(&query, "224.0.0.251:5353");

    // Also send a general query to discover .local hosts
    let query2 = build_mdns_any_query();
    let _ = sock.send_to(&query2, "224.0.0.251:5353");

    let mut seen = HashSet::new();
    let mut buf = [0u8; 1500];

    loop {
        match sock.recv_from(&mut buf) {
            Ok((len, addr)) => {
                if let std::net::SocketAddr::V4(v4) = addr {
                    let ip = *v4.ip();
                    if ip == local_ip {
                        continue;
                    }
                    if seen.insert(ip) {
                        let hostname = parse_mdns_response(&buf[..len]);
                        hits.push(ProbeHit {
                            ip,
                            mac: None,
                            hostname,
                            method: "mDNS",
                        });
                    }
                }
            }
            Err(_) => break,
        }
    }

    let _ = sock.leave_multicast_v4(&Ipv4Addr::new(224, 0, 0, 251), &local_ip);
    hits
}

fn build_mdns_services_query() -> Vec<u8> {
    let mut pkt = Vec::with_capacity(64);
    pkt.extend_from_slice(&[0x00, 0x00]); // ID
    pkt.extend_from_slice(&[0x00, 0x00]); // Flags
    pkt.extend_from_slice(&[0x00, 0x01]); // Questions: 1
    pkt.extend_from_slice(&[0x00, 0x00]); // Answers
    pkt.extend_from_slice(&[0x00, 0x00]); // Authority
    pkt.extend_from_slice(&[0x00, 0x00]); // Additional
    // _services._dns-sd._udp.local PTR
    encode_dns_name(&mut pkt, "_services._dns-sd._udp.local");
    pkt.extend_from_slice(&[0x00, 0x0C]); // Type: PTR
    pkt.extend_from_slice(&[0x00, 0x01]); // Class: IN
    pkt
}

fn build_mdns_any_query() -> Vec<u8> {
    let mut pkt = Vec::with_capacity(32);
    pkt.extend_from_slice(&[0x00, 0x00]); // ID
    pkt.extend_from_slice(&[0x00, 0x00]); // Flags
    pkt.extend_from_slice(&[0x00, 0x01]); // Questions: 1
    pkt.extend_from_slice(&[0x00, 0x00]);
    pkt.extend_from_slice(&[0x00, 0x00]);
    pkt.extend_from_slice(&[0x00, 0x00]);
    // Query for "local" domain with ANY type
    encode_dns_name(&mut pkt, "local");
    pkt.extend_from_slice(&[0x00, 0xFF]); // Type: ANY
    pkt.extend_from_slice(&[0x00, 0x01]); // Class: IN
    pkt
}

fn encode_dns_name(pkt: &mut Vec<u8>, name: &str) {
    for label in name.split('.') {
        pkt.push(label.len() as u8);
        pkt.extend_from_slice(label.as_bytes());
    }
    pkt.push(0);
}

fn parse_mdns_response(data: &[u8]) -> Option<String> {
    if data.len() < 12 {
        return None;
    }

    // Try to extract a hostname from answer or additional sections
    let an_count = u16::from_be_bytes([data[6], data[7]]) as usize;
    let _ns_count = u16::from_be_bytes([data[8], data[9]]) as usize;
    let ar_count = u16::from_be_bytes([data[10], data[11]]) as usize;

    if an_count == 0 && ar_count == 0 {
        return None;
    }

    // Skip questions
    let qd_count = u16::from_be_bytes([data[4], data[5]]) as usize;
    let mut pos = 12;
    for _ in 0..qd_count {
        pos = skip_dns_name(data, pos)?;
        pos += 4; // type + class
    }

    // Scan answer + authority + additional sections for useful names
    let total_rr = an_count + _ns_count + ar_count;
    for _ in 0..total_rr {
        if pos >= data.len() {
            break;
        }
        let name = read_dns_name(data, pos);
        pos = skip_dns_name(data, pos)?;
        if pos + 10 > data.len() {
            break;
        }
        let _rtype = u16::from_be_bytes([data[pos], data[pos + 1]]);
        let rdlen = u16::from_be_bytes([data[pos + 8], data[pos + 9]]) as usize;
        pos += 10 + rdlen;

        // Return the first clean hostname
        if let Some(n) = name {
            let clean = n
                .trim_end_matches(".local")
                .trim_end_matches('.')
                .to_string();
            if !clean.is_empty() && !clean.starts_with('_') && !clean.contains("._") {
                return Some(clean);
            }
        }
    }

    None
}

fn skip_dns_name(data: &[u8], mut pos: usize) -> Option<usize> {
    loop {
        if pos >= data.len() {
            return None;
        }
        let len = data[pos] as usize;
        if len == 0 {
            return Some(pos + 1);
        }
        if len >= 0xC0 {
            return Some(pos + 2);
        } // pointer
        pos += 1 + len;
    }
}

fn read_dns_name(data: &[u8], mut pos: usize) -> Option<String> {
    let mut name = String::new();
    let mut jumps = 0;
    loop {
        if pos >= data.len() || jumps > 10 {
            return None;
        }
        let len = data[pos] as usize;
        if len == 0 {
            break;
        }
        if len >= 0xC0 {
            let off = ((len & 0x3F) << 8) | (data.get(pos + 1).copied()? as usize);
            pos = off;
            jumps += 1;
            continue;
        }
        pos += 1;
        if pos + len > data.len() {
            return None;
        }
        if !name.is_empty() {
            name.push('.');
        }
        name.push_str(&String::from_utf8_lossy(&data[pos..pos + len]));
        pos += len;
    }
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 7: SSDP/UPnP Discovery (UDP 1900)
// ═════════════════════════════════════════════════════════════════════════════

pub(crate) fn ssdp_discover(local_ip: Ipv4Addr) -> Vec<ProbeHit> {
    let mut hits = Vec::new();

    let sock = match UdpSocket::bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) {
        Ok(s) => s,
        Err(_) => return hits,
    };
    let _ = sock.set_read_timeout(Some(Duration::from_millis(2000)));

    let msearch = b"M-SEARCH * HTTP/1.1\r\n\
        HOST: 239.255.255.250:1900\r\n\
        MAN: \"ssdp:discover\"\r\n\
        MX: 1\r\n\
        ST: ssdp:all\r\n\
        \r\n";

    let _ = sock.send_to(msearch, "239.255.255.250:1900");

    let mut seen = HashSet::new();
    let mut buf = [0u8; 2048];

    loop {
        match sock.recv_from(&mut buf) {
            Ok((len, addr)) => {
                if let std::net::SocketAddr::V4(v4) = addr {
                    let ip = *v4.ip();
                    if ip == local_ip {
                        continue;
                    }
                    if seen.insert(ip) {
                        let resp = String::from_utf8_lossy(&buf[..len]);
                        let server = resp
                            .lines()
                            .find(|l| l.to_lowercase().starts_with("server:"))
                            .map(|l| l[7..].trim().to_string());
                        hits.push(ProbeHit {
                            ip,
                            mac: None,
                            hostname: server,
                            method: "SSDP",
                        });
                    }
                }
            }
            Err(_) => break,
        }
    }

    hits
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 8: DNS PTR Reverse Lookup (getnameinfo)
// ═════════════════════════════════════════════════════════════════════════════

pub(crate) fn dns_reverse_scan(targets: &[Ipv4Addr]) -> Vec<ProbeHit> {
    let hits: Mutex<Vec<ProbeHit>> = Mutex::new(Vec::new());

    for chunk in targets.chunks(32) {
        thread::scope(|s| {
            for &target in chunk {
                let h = &hits;
                s.spawn(move || {
                    if let Some(name) = reverse_dns(target) {
                        h.lock().unwrap().push(ProbeHit {
                            ip: target,
                            mac: None,
                            hostname: Some(name),
                            method: "DNS-PTR",
                        });
                    }
                });
            }
        });
    }

    hits.into_inner().unwrap()
}

fn reverse_dns(ip: Ipv4Addr) -> Option<String> {
    let ip_u32 = u32::from(ip).to_be();
    let sa = SOCKADDR_IN {
        sin_family: AF_INET,
        sin_port: 0,
        sin_addr: ip_u32,
        sin_zero: [0; 8],
    };

    let mut host = [0u8; 256];
    let ret = unsafe {
        getnameinfo(
            &sa,
            std::mem::size_of::<SOCKADDR_IN>() as i32,
            host.as_mut_ptr(),
            host.len() as u32,
            std::ptr::null_mut(),
            0,
            NI_NAMEREQD,
        )
    };

    if ret == 0 {
        let end = host.iter().position(|&b| b == 0).unwrap_or(host.len());
        let name = String::from_utf8_lossy(&host[..end]).to_string();
        // Don't return if it's just the IP as a string
        if name != ip.to_string() && !name.is_empty() {
            return Some(name);
        }
    }
    None
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 9: LLMNR Discovery (UDP 5355 multicast)
// ═════════════════════════════════════════════════════════════════════════════

pub(crate) fn llmnr_discover(local_ip: Ipv4Addr) -> Vec<ProbeHit> {
    let mut hits = Vec::new();

    let sock = match UdpSocket::bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) {
        Ok(s) => s,
        Err(_) => return hits,
    };
    let _ = sock.set_read_timeout(Some(Duration::from_millis(1500)));

    // Join LLMNR multicast group
    let _ = sock.join_multicast_v4(&Ipv4Addr::new(224, 0, 0, 252), &local_ip);

    // Query commonly-used LLMNR names to solicit responses
    for name in &[b"wpad" as &[u8], b"isatap", b"localhost"] {
        let query = build_llmnr_query(name);
        let _ = sock.send_to(&query, "224.0.0.252:5355");
    }

    let mut seen = HashSet::new();
    let mut buf = [0u8; 1500];

    loop {
        match sock.recv_from(&mut buf) {
            Ok((_len, addr)) => {
                if let std::net::SocketAddr::V4(v4) = addr {
                    let ip = *v4.ip();
                    if ip == local_ip {
                        continue;
                    }
                    if seen.insert(ip) {
                        hits.push(ProbeHit {
                            ip,
                            mac: None,
                            hostname: None,
                            method: "LLMNR",
                        });
                    }
                }
            }
            Err(_) => break,
        }
    }

    let _ = sock.leave_multicast_v4(&Ipv4Addr::new(224, 0, 0, 252), &local_ip);
    hits
}

fn build_llmnr_query(name: &[u8]) -> Vec<u8> {
    let mut pkt = Vec::with_capacity(32 + name.len());
    pkt.extend_from_slice(&[0x00, 0x01]); // ID
    pkt.extend_from_slice(&[0x00, 0x00]); // Flags: query
    pkt.extend_from_slice(&[0x00, 0x01]); // Questions: 1
    pkt.extend_from_slice(&[0x00, 0x00]);
    pkt.extend_from_slice(&[0x00, 0x00]);
    pkt.extend_from_slice(&[0x00, 0x00]);
    // Question name
    pkt.push(name.len() as u8);
    pkt.extend_from_slice(name);
    pkt.push(0); // end
    pkt.extend_from_slice(&[0x00, 0x01]); // Type: A
    pkt.extend_from_slice(&[0x00, 0x01]); // Class: IN
    pkt
}

// ═════════════════════════════════════════════════════════════════════════════
// Method 10: NetBIOS Broadcast (subnet broadcast to UDP 137)
// ═════════════════════════════════════════════════════════════════════════════

pub(crate) fn nbt_broadcast(local_ip: Ipv4Addr, mask: Ipv4Addr) -> Vec<ProbeHit> {
    let mut hits = Vec::new();

    let broadcast = {
        let ip_u32 = u32::from(local_ip);
        let mask_u32 = u32::from(mask);
        Ipv4Addr::from(ip_u32 | !mask_u32)
    };

    let sock = match UdpSocket::bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) {
        Ok(s) => s,
        Err(_) => return hits,
    };
    let _ = sock.set_broadcast(true);
    let _ = sock.set_read_timeout(Some(Duration::from_millis(1500)));

    let query = build_nbt_broadcast_query();
    let _ = sock.send_to(&query, SocketAddrV4::new(broadcast, 137));

    let mut seen = HashSet::new();
    let mut buf = [0u8; 512];

    loop {
        match sock.recv_from(&mut buf) {
            Ok((len, addr)) => {
                if let std::net::SocketAddr::V4(v4) = addr {
                    let ip = *v4.ip();
                    if ip == local_ip {
                        continue;
                    }
                    if seen.insert(ip) {
                        let hostname = parse_nbstat_response(&buf[..len]);
                        hits.push(ProbeHit {
                            ip,
                            mac: None,
                            hostname,
                            method: "NBT-BC",
                        });
                    }
                }
            }
            Err(_) => break,
        }
    }

    hits
}

fn build_nbt_broadcast_query() -> Vec<u8> {
    let mut pkt = Vec::with_capacity(50);
    pkt.extend_from_slice(&[0x00, 0x02]); // Transaction ID
    pkt.extend_from_slice(&[0x01, 0x10]); // Flags: broadcast, recursion desired
    pkt.extend_from_slice(&[0x00, 0x01]); // Questions: 1
    pkt.extend_from_slice(&[0x00, 0x00]);
    pkt.extend_from_slice(&[0x00, 0x00]);
    pkt.extend_from_slice(&[0x00, 0x00]);
    // Name: "*" (wildcard) encoded
    pkt.push(0x20);
    pkt.extend_from_slice(b"CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    pkt.push(0x00);
    pkt.extend_from_slice(&[0x00, 0x21]); // Type: NBSTAT
    pkt.extend_from_slice(&[0x00, 0x01]); // Class: IN
    pkt
}

// ─── Public ARP cache reader (for instant first-pass) ───────────────────────

/// An ARP cache entry with interface index, IP, and optional MAC.
pub struct ArpCacheEntry {
    /// Interface index from the OS ARP table.
    pub if_index: u32,
    /// IPv4 address of the neighbor.
    pub ip: Ipv4Addr,
    /// MAC address (if available, 6+ byte physical address).
    pub mac: Option<String>,
}

/// Read ALL entries from the OS ARP cache (GetIpNetTable).
/// This is instant, zero network traffic, and returns entries from all interfaces.
/// Filters out invalid entries (type < 3).
pub(crate) fn arp_cache_read_all() -> Vec<ArpCacheEntry> {
    let mut entries = Vec::new();

    unsafe {
        let mut size: u32 = 0;
        let ret = GetIpNetTable(std::ptr::null_mut(), &mut size, 0);
        if ret != ERROR_BUFFER_OVERFLOW || size == 0 {
            return entries;
        }

        let mut buf = vec![0u8; size as usize];
        let ret = GetIpNetTable(buf.as_mut_ptr(), &mut size, 0);
        if ret != ERROR_SUCCESS {
            return entries;
        }

        let num_entries = *(buf.as_ptr() as *const u32);
        let rows_ptr = buf.as_ptr().add(4) as *const MIB_IPNETROW;

        for i in 0..num_entries as usize {
            let row = &*rows_ptr.add(i);
            // 3=dynamic, 4=static; skip invalid(2) and other(1)
            if row.dwType < 3 {
                continue;
            }
            let ip = Ipv4Addr::from(u32::from_be(row.dwAddr));

            // Skip link-local and broadcast
            let octets = ip.octets();
            if octets[0] == 169 && octets[1] == 254 {
                continue;
            }
            if octets[0] == 255 || ip.is_broadcast() || ip.is_loopback() {
                continue;
            }
            // Skip multicast (224-239.x.x.x)
            if octets[0] >= 224 && octets[0] <= 239 {
                continue;
            }

            let mac = if row.dwPhysAddrLen >= 6 {
                Some(format_mac(&row.bPhysAddr[..6].try_into().unwrap()))
            } else {
                None
            };

            entries.push(ArpCacheEntry {
                if_index: row.dwIndex,
                ip,
                mac,
            });
        }
    }

    entries
}

// ─── Helpers ────────────────────────────────────────────────────────────────

pub(crate) fn format_mac(bytes: &[u8; 6]) -> String {
    format!(
        "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]
    )
}