pingr 0.3.9

A blazing fast network scanner with beautiful terminal output and multiple export formats
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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
use clap::{Parser, ValueEnum};
use colored::*;
use dns_lookup::lookup_addr;
use hickory_resolver::config::{NameServerConfig, Protocol, ResolverConfig, ResolverOpts};
use hickory_resolver::TokioAsyncResolver;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use ipnet::Ipv4Net;
use regex::Regex;
use serde_json::json;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream, UdpSocket};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use surge_ping::{Client, Config, PingIdentifier, PingSequence};
use tokio::signal;
use tokio::sync::{Mutex, Semaphore};

#[derive(Parser, Debug)]
#[clap(author, version, about = "A blazing fast network scanner with beautiful terminal output", long_about = None)]
struct Args {
    /// Network to scan in CIDR notation (can specify multiple)
    cidr: Option<Vec<String>>,

    /// Input file containing IP addresses and/or CIDR ranges (one per line)
    #[clap(short = 'i', long = "input")]
    input_file: Option<String>,

    /// Show unreachable hosts
    #[clap(short, long)]
    verbose: bool,

    /// Number of concurrent pings (auto = automatic optimization)
    #[clap(short = 't', long = "threads", default_value = "auto")]
    concurrency: String,

    /// Output file path (without extension)
    #[clap(short, long)]
    output: Option<String>,

    /// Output format
    #[clap(short = 'f', long, value_enum, default_value = "text")]
    format: OutputFormat,

    /// Suppress colorized output
    #[clap(long)]
    no_color: bool,

    /// Quiet mode (minimal output - IP addresses only)
    #[clap(short = 'q', long)]
    quiet: bool,

    /// Number of ping attempts per host
    #[clap(short = 'c', long = "count", default_value = "1")]
    ping_count: u8,

    /// Ping timeout in seconds
    #[clap(long = "timeout", default_value = "1")]
    timeout: u64,

    /// Skip hostname resolution
    #[clap(short = 'n', long = "no-resolve")]
    no_resolve: bool,

    /// Show detailed statistics (scan time, RTT stats, success rate)
    #[clap(long = "stats")]
    stats: bool,

    /// Disable adaptive timeout
    #[clap(long = "no-adaptive")]
    no_adaptive: bool,

    /// Rate limit (pings per second, 0 = unlimited)
    #[clap(long = "rate", default_value = "0")]
    rate_limit: u32,

    /// Export format for integration (csv, xml, nmap)
    #[clap(long = "export")]
    export_format: Option<String>,

    /// Auto-save results on interrupt
    #[clap(long = "autosave", default_value = "true")]
    autosave: bool,

    /// Simple mode - just output IP addresses (overrides other display options)
    #[clap(short = 's', long = "simple")]
    simple: bool,

    /// Custom DNS server for hostname resolution (e.g., domain controller IP)
    #[clap(long = "dns-server")]
    dns_server: Option<String>,

    /// Use NetBIOS name resolution instead of DNS (great for Windows networks)
    #[clap(long = "netbios")]
    use_netbios: bool,

    /// Use SMB hostname query (port 445, most reliable for Windows)
    #[clap(long = "smb")]
    use_smb: bool,

    /// Scan for web servers on live hosts and extract status/title
    #[clap(long = "web-server")]
    web_server: bool,
}

#[derive(Debug, Clone, ValueEnum)]
enum OutputFormat {
    Text,
    Json,
    Both,
}

#[derive(Debug, Clone)]
struct HostInfo {
    ip: Ipv4Addr,
    hostname: Option<String>,
    rtt: Option<Duration>,
    attempts: u8,
    network: String,
}

#[derive(Debug, Clone)]
struct WebServerInfo {
    ip: Ipv4Addr,
    hostname: Option<String>,
    port: u16,
    protocol: String,
    status_code: u16,
    title: Option<String>,
}

struct ScanResult {
    alive_hosts: Vec<HostInfo>,
    dead_hosts: Vec<Ipv4Addr>,
    scan_duration: Duration,
    total_scanned: usize,
    avg_rtt: Option<Duration>,
    min_rtt: Option<Duration>,
    max_rtt: Option<Duration>,
    interrupted: bool,
    networks_scanned: Vec<String>,
}

// Global flag for interrupt handling
static INTERRUPTED: AtomicBool = AtomicBool::new(false);

/// Query NetBIOS name for an IP address
/// Returns the NetBIOS hostname if found
fn query_netbios_name(ip: Ipv4Addr, timeout: Duration) -> Option<String> {
    // Create NetBIOS Name Query packet
    let mut query = Vec::new();

    // Transaction ID (random)
    query.extend_from_slice(&[0x13, 0x37]);

    // Flags: 0x0010 (standard query)
    query.extend_from_slice(&[0x00, 0x10]);

    // Questions: 1
    query.extend_from_slice(&[0x00, 0x01]);

    // Answer RRs: 0
    query.extend_from_slice(&[0x00, 0x00]);

    // Authority RRs: 0
    query.extend_from_slice(&[0x00, 0x00]);

    // Additional RRs: 0
    query.extend_from_slice(&[0x00, 0x00]);

    // Query name: "*" (0x2A) encoded as NetBIOS name
    // NetBIOS names are 16 bytes, encoded as 32 bytes
    query.push(0x20); // Length of encoded name (32 bytes)

    // Encode "*" (wildcard) as NetBIOS name
    // Each character is split into two nibbles and offset by 'A' (0x41)
    for _ in 0..15 {
        query.push(0x43); // 'C' represents 0x20 (space)
        query.push(0x41); // 'A'
    }
    // Last byte is 0x00 (workstation service)
    query.push(0x43);
    query.push(0x41);

    query.push(0x00); // End of name

    // Question Type: NBSTAT (0x0021)
    query.extend_from_slice(&[0x00, 0x21]);

    // Question Class: IN (0x0001)
    query.extend_from_slice(&[0x00, 0x01]);

    // Send query via UDP to port 137
    let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
    socket.set_read_timeout(Some(timeout)).ok()?;
    socket.set_write_timeout(Some(timeout)).ok()?;

    let addr = SocketAddr::new(IpAddr::V4(ip), 137);
    socket.send_to(&query, addr).ok()?;

    // Receive response
    let mut response = [0u8; 512];
    let (size, _) = match socket.recv_from(&mut response) {
        Ok(result) => result,
        Err(_) => {
            return None;
        }
    };

    if size < 56 {
        return None;
    }

    // Parse response to extract hostname
    // Skip header (12 bytes) + question section
    // The answer section starts around byte 56
    let offset = 56;

    // Extract hostname from first entry in name table
    if offset + 18 <= size {
        let name_bytes = &response[offset..offset + 15];
        let name = String::from_utf8_lossy(name_bytes)
            .trim()
            .trim_end_matches('\0')
            .to_string();

        if !name.is_empty() && name != "*" {
            return Some(name);
        }
    }

    None
}

/// Query SMB hostname via SMB2 protocol
/// Returns the hostname from SMB server
fn query_smb_hostname(ip: Ipv4Addr, timeout: Duration) -> Option<String> {
    use std::io::Read;

    // Connect to SMB port 445
    let addr = SocketAddr::new(IpAddr::V4(ip), 445);
    let mut stream = TcpStream::connect_timeout(&addr, timeout).ok()?;
    stream.set_read_timeout(Some(timeout)).ok()?;
    stream.set_write_timeout(Some(timeout)).ok()?;

    // SMB2 Negotiate Request
    let mut negotiate = Vec::new();

    // NetBIOS Session Service header
    negotiate.push(0x00); // Message type: Session message
    negotiate.extend_from_slice(&[0x00, 0x00, 0x85]); // Length: 133 bytes

    // SMB2 Header
    negotiate.extend_from_slice(&[0xFE, b'S', b'M', b'B']); // Protocol ID: SMB2
    negotiate.extend_from_slice(&[0x40, 0x00]); // Header length: 64
    negotiate.extend_from_slice(&[0x00, 0x00]); // Credit charge
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Status
    negotiate.extend_from_slice(&[0x00, 0x00]); // Command: Negotiate (0x0000)
    negotiate.extend_from_slice(&[0x00, 0x00]); // Credits requested
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Flags
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // NextCommand
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // MessageId
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Reserved
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // TreeId
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // SessionId
    negotiate.extend_from_slice(&[0x00; 16]); // Signature

    // SMB2 Negotiate Request structure
    negotiate.extend_from_slice(&[0x24, 0x00]); // StructureSize: 36
    negotiate.extend_from_slice(&[0x05, 0x00]); // DialectCount: 5
    negotiate.extend_from_slice(&[0x01, 0x00]); // SecurityMode: Signing enabled
    negotiate.extend_from_slice(&[0x00, 0x00]); // Reserved
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Capabilities
    negotiate.extend_from_slice(&[0x00; 16]); // ClientGuid
    negotiate.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // ClientStartTime

    // Dialects: SMB 2.0.2, 2.1, 3.0, 3.0.2, 3.1.1
    negotiate.extend_from_slice(&[0x02, 0x02]); // SMB 2.0.2
    negotiate.extend_from_slice(&[0x10, 0x02]); // SMB 2.1
    negotiate.extend_from_slice(&[0x00, 0x03]); // SMB 3.0
    negotiate.extend_from_slice(&[0x02, 0x03]); // SMB 3.0.2
    negotiate.extend_from_slice(&[0x11, 0x03]); // SMB 3.1.1

    // Send negotiate request
    stream.write_all(&negotiate).ok()?;

    // Read response
    let mut response = vec![0u8; 1024];
    let size = stream.read(&mut response).ok()?;

    if size < 68 {
        return None;
    }

    // Parse SMB2 Negotiate Response
    // Skip NetBIOS header (4 bytes) and SMB2 header (64 bytes)
    // The server name might be in the SecurityBuffer or we need to do Session Setup

    // Try to extract hostname from various locations in the response
    // SMB responses often contain the hostname in various fields
    for window in response[68..size].windows(16) {
        if let Ok(s) = std::str::from_utf8(window) {
            let cleaned: String = s.chars()
                .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
                .collect();

            if cleaned.len() >= 4 && cleaned.len() <= 15 && !cleaned.chars().all(|c| c.is_ascii_digit()) {
                return Some(cleaned);
            }
        }
    }

    None
}

/// Scan for web servers on common ports (highly concurrent)
async fn scan_web_servers(hosts: &[HostInfo]) -> Vec<WebServerInfo> {
    use tokio::sync::Semaphore;
    use std::sync::Arc;

    // Common web server ports
    let ports = vec![
        80, 443, 8000, 8001, 8443, 8080, 8081, 9000, 9001,
        2083, 2087, 8060, 8090, 8880, 9043, 10000, 902,
        4343, 5985, 9389
    ];

    let client = Arc::new(reqwest::Client::builder()
        .timeout(Duration::from_secs(2))
        .danger_accept_invalid_certs(true)
        .build()
        .unwrap());

    let title_regex = Arc::new(Regex::new(r"<title[^>]*>(.*?)</title>").unwrap());

    // Limit concurrent requests to avoid overwhelming the system
    let semaphore = Arc::new(Semaphore::new(500));

    println!("\n{} Scanning for web servers on {} hosts across {} ports...", "🌐".cyan(), hosts.len(), ports.len());

    let mut tasks = Vec::new();

    // Create all scanning tasks
    for host in hosts {
        for &port in &ports {
            let client = Arc::clone(&client);
            let regex = Arc::clone(&title_regex);
            let sem = Arc::clone(&semaphore);
            let ip = host.ip;
            let hostname = host.hostname.clone();

            let task = tokio::spawn(async move {
                let _permit = sem.acquire().await.unwrap();

                // Determine which protocol to try first
                let (primary, secondary) = if port == 443 || port == 8443 || port == 2083 || port == 2087 || port == 9043 {
                    ("https", "http")
                } else {
                    ("http", "https")
                };

                // Try primary protocol first
                for protocol in [primary, secondary] {
                    let url = format!("{}://{}:{}", protocol, ip, port);

                    if let Ok(response) = client.get(&url).send().await {
                        let status = response.status().as_u16();
                        let body = response.text().await.ok();

                        let title = body.as_ref().and_then(|html| {
                            regex.captures(html)
                                .and_then(|cap| cap.get(1))
                                .map(|m| m.as_str().trim().to_string())
                        });

                        return Some(WebServerInfo {
                            ip,
                            hostname: hostname.clone(),
                            port,
                            protocol: protocol.to_string(),
                            status_code: status,
                            title,
                        });
                    }
                }

                None
            });

            tasks.push(task);
        }
    }

    // Wait for all tasks and collect results
    let mut web_servers = Vec::new();
    for task in tasks {
        if let Ok(Some(info)) = task.await {
            web_servers.push(info);
        }
    }

    web_servers
}

/// Display web server scan results
fn display_web_servers(servers: &[WebServerInfo]) {
    if servers.is_empty() {
        println!("\n{} {}", "β„Ή".blue(), "No web servers found".white());
        return;
    }

    println!(
        "\n{}",
        "═══════════════════════════════════════════════════════"
            .blue()
            .bold()
    );
    println!(
        "{}",
        format!("    🌐 Found {} Web Servers    ", servers.len())
            .cyan()
            .bold()
    );
    println!(
        "{}",
        "═══════════════════════════════════════════════════════"
            .blue()
            .bold()
    );

    for server in servers {
        let status_color = if server.status_code < 300 {
            server.status_code.to_string().green()
        } else if server.status_code < 400 {
            server.status_code.to_string().yellow()
        } else {
            server.status_code.to_string().red()
        };

        let host_display = if let Some(ref hostname) = server.hostname {
            format!("{} ({})", server.ip, hostname.cyan())
        } else {
            server.ip.to_string()
        };

        println!("\n  {} {}", "πŸ”—".white(), host_display.white().bold());
        println!(
            "    {} {}://{}:{} - {}",
            "β”œβ”€".blue(),
            server.protocol.cyan(),
            server.ip,
            server.port.to_string().yellow(),
            status_color.bold()
        );

        if let Some(ref title) = server.title {
            println!("    {} Title: {}", "└─".blue(), title.white());
        }
    }

    println!(
        "\n{}",
        "═══════════════════════════════════════════════════════"
            .blue()
            .bold()
    );
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();

    if args.no_color {
        colored::control::set_override(false);
    }

    // Parse input networks from file or command line
    let networks = parse_input_networks(&args)?;

    // Show help if no networks provided
    if networks.is_empty() {
        print_help();
        std::process::exit(0);
    }

    // Setup interrupt handler
    let interrupted = Arc::new(AtomicBool::new(false));
    let interrupted_clone = interrupted.clone();
    let simple = args.simple;
    let quiet = args.quiet;

    tokio::spawn(async move {
        signal::ctrl_c().await.expect("Failed to listen for Ctrl-C");
        if !simple && !quiet {
            println!(
                "\n{} {}",
                "⚠".yellow().bold(),
                "Interrupt received! Saving partial results...".yellow()
            );
        }
        interrupted_clone.store(true, Ordering::Relaxed);
        INTERRUPTED.store(true, Ordering::Relaxed);
    });

    // Shared results storage for graceful shutdown
    let all_alive_hosts = Arc::new(Mutex::new(Vec::new()));
    let all_dead_hosts = Arc::new(Mutex::new(Vec::new()));

    // Calculate total hosts
    let mut total_hosts = 0;
    let mut network_details = Vec::new();

    for cidr in &networks {
        match Ipv4Net::from_str(cidr) {
            Ok(net) => {
                let host_count = net.hosts().count();
                total_hosts += host_count;
                network_details.push((cidr.clone(), net, host_count));
            }
            Err(e) => {
                if !args.simple && !args.quiet {
                    eprintln!("{} Invalid CIDR '{}': {}", "⚠".yellow(), cidr, e);
                }
            }
        }
    }

    if !args.quiet && !args.simple {
        print_banner_multi(&network_details, total_hosts, &args);
    }

    let start_time = Instant::now();

    // Determine concurrency for total hosts
    let concurrency =
        determine_concurrency(&args.concurrency, total_hosts, args.simple || args.quiet)?;

    // Create progress bar for all networks
    let multi_progress = MultiProgress::new();
    let main_pb = if !args.quiet && !args.simple {
        let pb = multi_progress.add(ProgressBar::new(total_hosts as u64));
        pb.set_style(
            ProgressStyle::default_bar()
                .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta}) {msg}")
                .unwrap()
                .progress_chars("β–ˆβ–‰β–Šβ–‹β–Œβ–β–Žβ–  "),
        );
        pb.set_message(format!("Scanning {} networks", networks.len()));
        Some(pb)
    } else {
        None
    };

    // Setup semaphore and rate limiter
    let semaphore = Arc::new(Semaphore::new(concurrency));
    let rate_limiter = if args.rate_limit > 0 {
        Some(Arc::new(tokio::sync::Semaphore::new(1)))
    } else {
        None
    };

    // Create ping client
    let config = Config::builder().kind(surge_ping::ICMP::V4).build();
    let client = match Client::new(&config) {
        Ok(c) => c,
        Err(e) => {
            if !args.simple {
                eprintln!(
                    "{} {}",
                    "βœ— Error:".red().bold(),
                    format!("Failed to create ping client: {}", e).red()
                );
                eprintln!(
                    "{} {}",
                    "β„Ή".blue(),
                    "Make sure you're running with sudo or have appropriate permissions".blue()
                );
            }
            std::process::exit(1);
        }
    };

    // Statistics tracking
    let success_count = Arc::new(AtomicUsize::new(0));
    let fail_count = Arc::new(AtomicUsize::new(0));

    let mut all_tasks = Vec::new();

    // Adaptive timeout logic
    let base_timeout = Duration::from_secs(args.timeout);
    let timeout_duration = if !args.no_adaptive {
        // Start with base timeout and adjust based on network conditions
        base_timeout
    } else {
        base_timeout
    };

    // Determine if we should resolve hostnames (default true unless --no-resolve)
    let should_resolve = !args.no_resolve;

    // Setup custom DNS resolver if specified
    let custom_resolver = if let Some(dns_server) = &args.dns_server {
        match dns_server.parse::<Ipv4Addr>() {
            Ok(dns_ip) => {
                let socket = SocketAddr::new(IpAddr::V4(dns_ip), 53);
                let mut config = ResolverConfig::new();
                config.add_name_server(NameServerConfig {
                    socket_addr: socket,
                    protocol: Protocol::Udp,
                    tls_dns_name: None,
                    trust_negative_responses: true,
                    bind_addr: None,
                });

                let resolver = TokioAsyncResolver::tokio(config, ResolverOpts::default());
                if !args.quiet && !args.simple {
                    println!(
                        "{} Using custom DNS server: {}",
                        "πŸ”".blue(),
                        dns_server.yellow().bold()
                    );
                }
                Some(Arc::new(resolver))
            }
            Err(e) => {
                if !args.simple {
                    eprintln!("{} Invalid DNS server IP: {}", "⚠".yellow(), e);
                }
                None
            }
        }
    } else {
        None
    };

    // Process each network
    for (cidr, net, _host_count) in network_details {
        if INTERRUPTED.load(Ordering::Relaxed) {
            break;
        }

        if !args.quiet && !args.simple {
            if let Some(pb) = &main_pb {
                pb.set_message(format!("Scanning {}", cidr.yellow()));
            }
        }

        // Generate tasks for this network
        for host in net.hosts() {
            if INTERRUPTED.load(Ordering::Relaxed) {
                break;
            }

            let client = client.clone();
            let sem = semaphore.clone();
            let pb_clone = main_pb.clone();
            let success = success_count.clone();
            let fail = fail_count.clone();
            let rate_limiter = rate_limiter.clone();
            let alive_hosts_clone = all_alive_hosts.clone();
            let dead_hosts_clone = all_dead_hosts.clone();
            let network_cidr = cidr.clone();
            let ping_count = args.ping_count;
            let resolve = should_resolve;
            let timeout = timeout_duration;
            let verbose = args.verbose;
            let simple = args.simple;
            let quiet = args.quiet;
            let resolver_clone = custom_resolver.clone();
            let use_netbios = args.use_netbios;
            let use_smb = args.use_smb;

            let task = tokio::spawn(async move {
                // Check if interrupted before starting
                if INTERRUPTED.load(Ordering::Relaxed) {
                    return;
                }

                // Rate limiting
                if let Some(limiter) = rate_limiter {
                    let _permit = limiter.acquire().await.unwrap();
                    tokio::time::sleep(Duration::from_millis(50)).await;
                }

                let _permit = sem.acquire().await.unwrap();

                // Check again after acquiring permit
                if INTERRUPTED.load(Ordering::Relaxed) {
                    return;
                }

                let mut successful_pings = 0;
                let mut total_rtt = Duration::ZERO;

                // Multiple ping attempts
                for attempt in 0..ping_count {
                    if let Some(rtt) =
                        ping_host_with_rtt(client.clone(), host, timeout, attempt).await
                    {
                        successful_pings += 1;
                        total_rtt += rtt;
                    }
                }

                if successful_pings > 0 {
                    success.fetch_add(1, Ordering::Relaxed);

                    let avg_rtt = total_rtt / successful_pings as u32;

                    // Resolve hostname if requested
                    let hostname = if resolve {
                        if use_smb {
                            // Use SMB hostname query
                            tokio::task::spawn_blocking(move || {
                                query_smb_hostname(host, Duration::from_secs(3))
                            })
                            .await
                            .ok()
                            .flatten()
                        } else if use_netbios {
                            // Use NetBIOS name resolution
                            tokio::task::spawn_blocking(move || {
                                query_netbios_name(host, Duration::from_secs(2))
                            })
                            .await
                            .ok()
                            .flatten()
                        } else if let Some(resolver) = resolver_clone {
                            // Use custom DNS resolver (async, no blocking needed)
                            match resolver.reverse_lookup(IpAddr::V4(host)).await {
                                Ok(lookup) => lookup.iter().next().map(|name| name.to_string()),
                                Err(_) => None,
                            }
                        } else {
                            // Use system DNS resolver via spawn_blocking
                            tokio::task::spawn_blocking(move || {
                                match lookup_addr(&IpAddr::V4(host)) {
                                    Ok(name) => Some(name),
                                    Err(_) => None,
                                }
                            })
                            .await
                            .ok()
                            .flatten()
                        }
                    } else {
                        None
                    };

                    if !simple && !quiet {
                        if let Some(pb) = &pb_clone {
                            let msg = if let Some(ref name) = hostname {
                                format!(
                                    "{} {} ({}) from {} ({}ms)",
                                    "Found:".green().bold(),
                                    host.to_string().green(),
                                    name.cyan(),
                                    network_cidr.yellow(),
                                    avg_rtt.as_millis()
                                )
                            } else {
                                format!(
                                    "{} {} from {} ({}ms)",
                                    "Found:".green().bold(),
                                    host.to_string().green(),
                                    network_cidr.yellow(),
                                    avg_rtt.as_millis()
                                )
                            };
                            pb.set_message(msg);
                        }
                    }

                    let host_info = HostInfo {
                        ip: host,
                        hostname,
                        rtt: Some(avg_rtt),
                        attempts: successful_pings,
                        network: network_cidr,
                    };

                    let mut hosts = alive_hosts_clone.lock().await;
                    hosts.push(host_info);
                } else {
                    fail.fetch_add(1, Ordering::Relaxed);
                    if verbose {
                        let mut hosts = dead_hosts_clone.lock().await;
                        hosts.push(host);
                    }
                }

                if let Some(pb) = pb_clone {
                    pb.inc(1);
                }
            });

            all_tasks.push(task);
        }
    }

    // Wait for all tasks or interruption
    for task in all_tasks {
        if INTERRUPTED.load(Ordering::Relaxed) {
            task.abort();
        } else {
            let _ = task.await;
        }
    }

    if let Some(pb) = main_pb {
        pb.finish_and_clear();
    }

    let scan_duration = start_time.elapsed();

    // Collect final results
    let mut alive_hosts = all_alive_hosts.lock().await.clone();
    let dead_hosts = all_dead_hosts.lock().await.clone();

    // Sort results
    alive_hosts.sort_by(|a, b| a.network.cmp(&b.network).then(a.ip.cmp(&b.ip)));

    // Calculate statistics only if needed
    let (avg_rtt, min_rtt, max_rtt) = if args.stats {
        let all_rtts: Vec<Duration> = alive_hosts.iter().filter_map(|h| h.rtt).collect();

        if !all_rtts.is_empty() {
            let sum: Duration = all_rtts.iter().sum();
            let avg = sum / all_rtts.len() as u32;
            let min = *all_rtts.iter().min().unwrap();
            let max = *all_rtts.iter().max().unwrap();
            (Some(avg), Some(min), Some(max))
        } else {
            (None, None, None)
        }
    } else {
        (None, None, None)
    };

    let was_interrupted = INTERRUPTED.load(Ordering::Relaxed);

    let result = ScanResult {
        alive_hosts: alive_hosts.clone(),
        dead_hosts: dead_hosts.clone(),
        scan_duration,
        total_scanned: success_count.load(Ordering::Relaxed) + fail_count.load(Ordering::Relaxed),
        avg_rtt,
        min_rtt,
        max_rtt,
        interrupted: was_interrupted,
        networks_scanned: networks,
    };

    // Display results
    if args.simple || args.quiet {
        // Simple mode - just output IP addresses
        for host in &result.alive_hosts {
            println!("{}", host.ip);
        }
    } else {
        display_results(&result, &args);
    }

    // Scan for web servers if requested
    if args.web_server && !result.alive_hosts.is_empty() && !args.simple {
        let web_servers = scan_web_servers(&result.alive_hosts).await;
        display_web_servers(&web_servers);
    }

    // Save to file if requested or if interrupted with autosave
    if args.output.is_some() || (was_interrupted && args.autosave && !args.simple) {
        let output_path = args.output.unwrap_or_else(|| {
            format!(
                "pingr_interrupted_{}",
                chrono::Local::now().format("%Y%m%d_%H%M%S")
            )
        });

        save_results(&result, &output_path, &args.format)?;

        if was_interrupted && !args.simple {
            println!(
                "{} Partial results saved to: {}",
                "πŸ’Ύ".green(),
                format!("{}.txt/json", output_path).white().bold()
            );
        }
    }

    // Export in special formats
    if let Some(export_format) = &args.export_format {
        export_results(&result, export_format)?;
    }

    Ok(())
}

fn print_help() {
    println!(
        "{}",
        "═══════════════════════════════════════════════════════"
            .blue()
            .bold()
    );
    println!(
        "{}",
        "                PINGR - Network Scanner v0.3.9          "
            .cyan()
            .bold()
    );
    println!(
        "{}",
        "═══════════════════════════════════════════════════════"
            .blue()
            .bold()
    );
    println!();
    println!("{}", "USAGE:".yellow().bold());
    println!("  {} <CIDR>... [OPTIONS]", "pingr".green());
    println!("  {} -i <FILE> [OPTIONS]", "pingr".green());
    println!();
    println!("{}", "EXAMPLES:".yellow().bold());
    println!("  {} 192.168.1.0/24", "pingr".green());
    println!("  {} 10.0.0.0/24 192.168.1.0/24", "pingr".green());
    println!("  {} -i targets.txt", "pingr".green());
    println!(
        "  {} -s 192.168.1.0/24        # Simple IP list output",
        "pingr".green()
    );
    println!(
        "  {} -n 192.168.1.0/24        # Skip hostname resolution",
        "pingr".green()
    );
    println!(
        "  {} --dns-server 10.0.0.1 192.168.1.0/24  # Use custom DNS server",
        "pingr".green()
    );
    println!(
        "  {} --netbios 192.168.1.0/24  # Use NetBIOS for Windows networks",
        "pingr".green()
    );
    println!(
        "  {} --smb 192.168.1.0/24      # Use SMB for Windows networks",
        "pingr".green()
    );
    println!(
        "  {} --stats 192.168.1.0/24   # Show detailed statistics",
        "pingr".green()
    );
    println!();
    println!("{}", "ARGUMENTS:".yellow().bold());
    println!("  {}         Network(s) in CIDR notation", "<CIDR>".cyan());
    println!();
    println!("{}", "OPTIONS:".yellow().bold());
    println!(
        "  {}, {}          Input file with targets",
        "-i".cyan(),
        "--input <FILE>".cyan()
    );
    println!(
        "  {}, {}         Simple mode - IP addresses only",
        "-s".cyan(),
        "--simple".cyan()
    );
    println!(
        "  {}, {}      Skip hostname resolution",
        "-n".cyan(),
        "--no-resolve".cyan()
    );
    println!(
        "  {}  <IP>     Custom DNS server (e.g., DC IP)",
        "--dns-server".cyan()
    );
    println!(
        "  {}          Use NetBIOS for Windows hostnames",
        "--netbios".cyan()
    );
    println!(
        "  {}              Use SMB for Windows hostnames (port 445)",
        "--smb".cyan()
    );
    println!(
        "  {}, {}         Quiet mode (minimal output)",
        "-q".cyan(),
        "--quiet".cyan()
    );
    println!(
        "  {}, {}       Show unreachable hosts",
        "-v".cyan(),
        "--verbose".cyan()
    );
    println!(
        "  {}, {} <N>   Concurrent threads (auto)",
        "-t".cyan(),
        "--threads".cyan()
    );
    println!(
        "  {}, {} <N>     Ping attempts per host (1)",
        "-c".cyan(),
        "--count".cyan()
    );
    println!(
        "  {}, {} <FILE>  Save results to file",
        "-o".cyan(),
        "--output".cyan()
    );
    println!(
        "  {}, {} <FMT>   Output format (text/json/both)",
        "-f".cyan(),
        "--format".cyan()
    );
    println!(
        "  {}      <SEC>  Ping timeout in seconds (1)",
        "--timeout".cyan()
    );
    println!(
        "  {}             Show detailed statistics",
        "--stats".cyan()
    );
    println!(
        "  {}         Disable adaptive timeout",
        "--no-adaptive".cyan()
    );
    println!("  {}          Disable colored output", "--no-color".cyan());
    println!(
        "  {} <FMT>      Export format (csv/nmap)",
        "--export".cyan()
    );
    println!(
        "  {}, {}          Show this help message",
        "-h".cyan(),
        "--help".cyan()
    );
    println!();
    println!("{}", "FEATURES:".yellow().bold());
    println!("  β€’ Automatic hostname resolution (use -n to disable)");
    println!("  β€’ SMB, NetBIOS, and custom DNS server support");
    println!("  β€’ Adaptive timeout enabled by default");
    println!("  β€’ Interrupt handling with auto-save (Ctrl-C)");
    println!("  β€’ Multi-network scanning support");
    println!("  β€’ Color-coded RTT for quick network health assessment");
    println!();
    println!("{}", "NOTE:".red().bold());
    println!(
        "  Requires {} or administrator privileges for ICMP",
        "sudo".yellow()
    );
    println!();
    println!(
        "{}",
        "For more information, visit: https://github.com/cybrly/pingr".blue()
    );
}

fn parse_input_networks(args: &Args) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let mut networks = Vec::new();

    // Parse from input file if provided
    if let Some(input_file) = &args.input_file {
        let file = File::open(input_file)?;
        let reader = BufReader::new(file);

        for line in reader.lines() {
            let line = line?;
            let trimmed = line.trim();

            // Skip empty lines and comments
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }

            // Check if it's a single IP or CIDR
            if trimmed.contains('/') {
                // CIDR notation
                networks.push(trimmed.to_string());
            } else if trimmed.parse::<Ipv4Addr>().is_ok() {
                // Single IP - convert to /32
                networks.push(format!("{}/32", trimmed));
            } else {
                if !args.simple && !args.quiet {
                    eprintln!("{} Invalid entry in input file: {}", "⚠".yellow(), trimmed);
                }
            }
        }

        if !args.simple && !args.quiet {
            println!(
                "{} Loaded {} networks from {}",
                "πŸ“".blue(),
                networks.len(),
                input_file.white().bold()
            );
        }
    }

    // Parse from command line arguments
    if let Some(cidrs) = &args.cidr {
        for cidr in cidrs {
            if cidr.contains('/') {
                networks.push(cidr.to_string());
            } else if cidr.parse::<Ipv4Addr>().is_ok() {
                networks.push(format!("{}/32", cidr));
            } else if !args.simple && !args.quiet {
                eprintln!("{} Invalid CIDR: {}", "⚠".yellow(), cidr);
            }
        }
    }

    Ok(networks)
}

fn print_banner_multi(
    network_details: &[(String, Ipv4Net, usize)],
    total_hosts: usize,
    args: &Args,
) {
    println!(
        "\n{}",
        "═══════════════════════════════════════════════════════"
            .blue()
            .bold()
    );
    println!(
        "{}",
        "                PINGR - Network Scanner v0.3.9          "
            .cyan()
            .bold()
    );
    println!(
        "{}",
        "═══════════════════════════════════════════════════════"
            .blue()
            .bold()
    );

    println!(
        "\n{} {} networks to scan:",
        "πŸ“‘".white(),
        network_details.len().to_string().yellow().bold()
    );
    for (cidr, _, host_count) in network_details.iter().take(5) {
        println!(
            "   {} {} ({} hosts)",
            "β”œβ”€".blue(),
            cidr.white(),
            host_count.to_string().yellow()
        );
    }
    if network_details.len() > 5 {
        println!(
            "   {} ... and {} more networks",
            "└─".blue(),
            (network_details.len() - 5).to_string().yellow()
        );
    }

    println!(
        "\n{} {}",
        "πŸ”’ Total hosts:".white().bold(),
        total_hosts.to_string().yellow()
    );
    println!(
        "{} {}",
        "πŸ”„ Ping attempts:".white().bold(),
        args.ping_count.to_string().yellow()
    );
    println!(
        "{} {}",
        "⏱️  Timeout:".white().bold(),
        format!("{}s", args.timeout).yellow()
    );

    if !args.no_resolve {
        if args.use_smb {
            println!(
                "{} {}",
                "πŸ” Name Resolution:".white().bold(),
                "SMB (port 445)".green()
            );
        } else if args.use_netbios {
            println!(
                "{} {}",
                "πŸ” Name Resolution:".white().bold(),
                "NetBIOS (port 137)".green()
            );
        } else {
            println!(
                "{} {}",
                "πŸ” DNS Resolution:".white().bold(),
                "Enabled".green()
            );
        }
    }

    if !args.no_adaptive {
        println!(
            "{} {}",
            "🎯 Adaptive Timeout:".white().bold(),
            "Enabled".green()
        );
    }

    if args.rate_limit > 0 {
        println!(
            "{} {}",
            "🚦 Rate Limit:".white().bold(),
            format!("{} pings/sec", args.rate_limit).yellow()
        );
    }

    println!(
        "{} {}",
        "πŸ›‘οΈ  Interrupt handling:".white().bold(),
        "Enabled (Ctrl-C to save partial results)".green()
    );

    println!("{}", "─".repeat(56).blue());
}

fn determine_concurrency(
    concurrency_str: &str,
    host_count: usize,
    quiet: bool,
) -> Result<usize, Box<dyn std::error::Error>> {
    if concurrency_str == "auto" {
        let optimal = match host_count {
            0..=256 => host_count.min(256),
            257..=1024 => 512,
            1025..=4096 => 1024,
            4097..=16384 => 2048,
            16385..=65536 => 4096,
            _ => 8192,
        };

        if !quiet {
            println!(
                "{} Auto-selected {} threads for {} hosts",
                "πŸ”§".blue(),
                optimal.to_string().yellow().bold(),
                host_count
            );
        }
        Ok(optimal)
    } else {
        Ok(concurrency_str.parse()?)
    }
}

async fn ping_host_with_rtt(
    client: Client,
    host: Ipv4Addr,
    timeout: Duration,
    sequence: u8,
) -> Option<Duration> {
    let payload = vec![0; 56];
    let mut pinger = client.pinger(IpAddr::V4(host), PingIdentifier(1)).await;
    pinger.timeout(timeout);

    let start = Instant::now();
    match pinger.ping(PingSequence(sequence as u16), &payload).await {
        Ok(_) => Some(start.elapsed()),
        Err(_) => None,
    }
}

fn display_results(result: &ScanResult, args: &Args) {
    let header = if result.interrupted {
        format!(
            "    ⚠ SCAN INTERRUPTED - Found {} Live Hosts    ",
            result.alive_hosts.len()
        )
        .yellow()
        .bold()
    } else {
        format!(
            "    βœ… SCAN COMPLETE - Found {} Live Hosts    ",
            result.alive_hosts.len()
        )
        .green()
        .bold()
    };

    println!(
        "\n{}",
        "═══════════════════════════════════════════════════════"
            .green()
            .bold()
    );
    println!("{}", header);
    println!(
        "{}",
        "═══════════════════════════════════════════════════════"
            .green()
            .bold()
    );

    if !result.alive_hosts.is_empty() {
        // Group hosts by network
        let mut by_network: std::collections::HashMap<String, Vec<&HostInfo>> =
            std::collections::HashMap::new();
        for host in &result.alive_hosts {
            by_network
                .entry(host.network.clone())
                .or_insert_with(Vec::new)
                .push(host);
        }

        println!("\n{}", "🟒 Live Hosts:".green().bold());
        println!("{}", "─".repeat(56).green());

        for network in &result.networks_scanned {
            if let Some(hosts) = by_network.get(network) {
                if result.networks_scanned.len() > 1 {
                    println!(
                        "\n  {} {} ({} hosts)",
                        "πŸ“".cyan(),
                        network.yellow().bold(),
                        hosts.len()
                    );
                }

                for (i, host) in hosts.iter().enumerate() {
                    let prefix = if result.networks_scanned.len() > 1 {
                        if i == hosts.len() - 1 {
                            "    └─"
                        } else {
                            "    β”œβ”€"
                        }
                    } else {
                        if i == hosts.len() - 1 {
                            "  └─"
                        } else {
                            "  β”œβ”€"
                        }
                    };

                    let mut info = host.ip.to_string();

                    // Show hostname if available
                    if let Some(hostname) = &host.hostname {
                        info = format!("{} ({})", info, hostname.cyan());
                    }

                    // Show RTT
                    if let Some(rtt) = host.rtt {
                        let rtt_color = if rtt.as_millis() < 10 {
                            format!("{}ms", rtt.as_millis()).green()
                        } else if rtt.as_millis() < 50 {
                            format!("{}ms", rtt.as_millis()).yellow()
                        } else {
                            format!("{}ms", rtt.as_millis()).red()
                        };
                        info = format!("{} - {}", info, rtt_color);
                    }

                    if args.ping_count > 1 {
                        info = format!("{} [{}/{} replies]", info, host.attempts, args.ping_count);
                    }

                    println!("{} {}", prefix.green(), info.white().bold());
                }
            }
        }
    } else {
        println!("\n{} {}", "⚠".yellow(), "No live hosts found".yellow());
    }

    if args.verbose && !result.dead_hosts.is_empty() {
        println!("\n{}", "πŸ”΄ Unreachable Hosts:".red().bold());
        println!("{}", "─".repeat(56).red());
        for host in &result.dead_hosts {
            println!("  └─ {}", host.to_string().red());
        }
    }

    // Only show statistics if --stats flag is used
    if args.stats {
        println!("\n{}", "πŸ“Š Statistics:".cyan().bold());
        println!("{}", "─".repeat(56).cyan());

        println!(
            "  {} {}",
            "Networks Scanned:".white(),
            result.networks_scanned.len().to_string().yellow()
        );
        println!(
            "  {} {}",
            "Total Scanned:".white(),
            result.total_scanned.to_string().yellow()
        );
        println!(
            "  {} {}",
            "Alive Hosts:".white(),
            result.alive_hosts.len().to_string().green()
        );

        // DNS Resolution statistics
        if !args.no_resolve {
            let resolved_count = result.alive_hosts.iter().filter(|h| h.hostname.is_some()).count();
            let resolved_pct = if !result.alive_hosts.is_empty() {
                (resolved_count as f32 / result.alive_hosts.len() as f32 * 100.0) as u32
            } else {
                0
            };
            println!(
                "  {} {}/{} ({}%)",
                "Hostnames Resolved:".white(),
                resolved_count.to_string().cyan(),
                result.alive_hosts.len().to_string().cyan(),
                resolved_pct.to_string().cyan()
            );
        }

        if args.verbose {
            println!(
                "  {} {}",
                "Dead Hosts:".white(),
                result.dead_hosts.len().to_string().red()
            );
        }

        // Success rate
        let success_rate = if result.total_scanned > 0 {
            (result.alive_hosts.len() as f32 / result.total_scanned as f32 * 100.0) as u32
        } else {
            0
        };

        let success_text = format!("{}%", success_rate);
        let colored_success = if success_rate > 50 {
            success_text.green()
        } else if success_rate > 20 {
            success_text.yellow()
        } else {
            success_text.red()
        };
        println!("  {} {}", "Success Rate:".white(), colored_success.bold());

        // RTT Statistics
        if let (Some(avg), Some(min), Some(max)) = (result.avg_rtt, result.min_rtt, result.max_rtt)
        {
            println!("\n  {} ", "RTT Statistics:".cyan().bold());
            println!(
                "    {} {}ms",
                "Min:".white(),
                min.as_millis().to_string().green()
            );
            println!(
                "    {} {}ms",
                "Avg:".white(),
                avg.as_millis().to_string().yellow()
            );
            println!(
                "    {} {}ms",
                "Max:".white(),
                max.as_millis().to_string().red()
            );
        }

        println!(
            "  {} {}",
            "Scan Time:".white(),
            format!("{:.2}s", result.scan_duration.as_secs_f32()).yellow()
        );

        let scan_rate = if result.scan_duration.as_secs_f32() > 0.0 {
            result.total_scanned as f32 / result.scan_duration.as_secs_f32()
        } else {
            0.0
        };
        println!(
            "  {} {}",
            "Scan Rate:".white(),
            format!("{:.0} hosts/sec", scan_rate).cyan()
        );
    }

    if result.interrupted {
        println!(
            "\n  {} {}",
            "Status:".white(),
            "INTERRUPTED - Partial results saved".yellow().bold()
        );
    }

    println!("{}", "═".repeat(56).blue().bold());
}

fn save_results(
    result: &ScanResult,
    output_path: &str,
    format: &OutputFormat,
) -> std::io::Result<()> {
    match format {
        OutputFormat::Text | OutputFormat::Both => {
            let txt_path = format!("{}.txt", output_path);
            let mut file = File::create(&txt_path)?;

            writeln!(file, "# Pingr Scan Results")?;
            writeln!(
                file,
                "# Generated: {}",
                chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
            )?;
            if result.interrupted {
                writeln!(file, "# Status: INTERRUPTED - Partial Results")?;
            }
            writeln!(
                file,
                "# Networks Scanned: {}",
                result.networks_scanned.join(", ")
            )?;
            writeln!(file, "# Alive Hosts: {}", result.alive_hosts.len())?;
            writeln!(file, "#")?;

            // Output IP addresses with hostnames if available
            for host in &result.alive_hosts {
                if let Some(hostname) = &host.hostname {
                    writeln!(file, "{}\t{}", host.ip, hostname)?;
                } else {
                    writeln!(file, "{}", host.ip)?;
                }
            }

            println!(
                "{} {}",
                "πŸ’Ύ Saved text output to:".green(),
                txt_path.white().bold()
            );
        }
        _ => {}
    }

    match format {
        OutputFormat::Json | OutputFormat::Both => {
            let json_path = format!("{}.json", output_path);

            let hosts_data: Vec<_> = result
                .alive_hosts
                .iter()
                .map(|h| {
                    json!({
                        "ip": h.ip.to_string(),
                        "hostname": h.hostname,
                        "network": h.network,
                        "rtt_ms": h.rtt.map(|r| r.as_millis()),
                        "successful_pings": h.attempts,
                    })
                })
                .collect();

            let json_data = json!({
                "scan_info": {
                    "timestamp": chrono::Local::now().to_rfc3339(),
                    "interrupted": result.interrupted,
                    "duration_seconds": result.scan_duration.as_secs_f32(),
                    "networks_scanned": result.networks_scanned,
                    "total_hosts": result.total_scanned,
                    "alive_count": result.alive_hosts.len(),
                    "dead_count": result.dead_hosts.len(),
                },
                "alive_hosts": hosts_data,
            });

            let mut file = File::create(&json_path)?;
            file.write_all(serde_json::to_string_pretty(&json_data)?.as_bytes())?;

            println!(
                "{} {}",
                "πŸ’Ύ Saved JSON output to:".green(),
                json_path.white().bold()
            );
        }
        _ => {}
    }

    Ok(())
}

fn export_results(result: &ScanResult, format: &str) -> std::io::Result<()> {
    match format {
        "csv" => {
            let filename = if result.interrupted {
                format!(
                    "pingr_export_interrupted_{}.csv",
                    chrono::Local::now().format("%Y%m%d_%H%M%S")
                )
            } else {
                "pingr_export.csv".to_string()
            };

            let mut file = File::create(&filename)?;
            writeln!(file, "IP,Hostname,Network,RTT_ms")?;

            for host in &result.alive_hosts {
                writeln!(
                    file,
                    "{},{},{},{}",
                    host.ip,
                    host.hostname.as_ref().unwrap_or(&String::from("")),
                    host.network,
                    host.rtt.map(|r| r.as_millis()).unwrap_or(0)
                )?;
            }

            println!(
                "{} {}",
                "πŸ“Š Exported CSV to:".green(),
                filename.white().bold()
            );
        }
        "nmap" => {
            let filename = if result.interrupted {
                format!(
                    "pingr_export_interrupted_{}.gnmap",
                    chrono::Local::now().format("%Y%m%d_%H%M%S")
                )
            } else {
                "pingr_export.gnmap".to_string()
            };

            let mut file = File::create(&filename)?;
            writeln!(
                file,
                "# Nmap 7.94 scan initiated {} as: pingr {}",
                chrono::Local::now().format("%Y-%m-%d %H:%M"),
                result.networks_scanned.join(" ")
            )?;

            for host in &result.alive_hosts {
                if let Some(hostname) = &host.hostname {
                    writeln!(file, "Host: {} ({}) Status: Up", host.ip, hostname)?;
                } else {
                    writeln!(file, "Host: {} () Status: Up", host.ip)?;
                }
            }

            println!(
                "{} {}",
                "πŸ—ΊοΈ  Exported nmap format to:".green(),
                filename.white().bold()
            );
        }
        _ => {
            eprintln!("{} Unknown export format: {}", "⚠".yellow(), format);
        }
    }

    Ok(())
}