ping-async 1.0.2

Unprivileged Async Ping
Documentation
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
// icmp.rs - ICMP packet construction and parsing module

use core::fmt;
use std::convert::TryFrom;
use std::io;
use std::net::IpAddr;

use crate::IcmpEchoStatus;

// ICMP error message type codes
const ICMPV4_DEST_UNREACHABLE: u8 = 3;
const ICMPV4_TIME_EXCEEDED: u8 = 11;
const ICMPV6_DEST_UNREACHABLE: u8 = 1;
const ICMPV6_TIME_EXCEEDED: u8 = 3;

// ICMP echo request type codes (for verifying embedded packets)
const ICMPV4_ECHO_REQUEST: u8 = 8;
const ICMPV6_ECHO_REQUEST: u8 = 128;

// IP protocol numbers
const IP_PROTO_ICMP: u8 = 1;
const IP_PROTO_ICMPV6: u8 = 58;

// Fixed IPv6 header length
const IPV6_HEADER_LEN: usize = 40;

/// Information extracted from an ICMP error message that embeds an original echo request.
pub struct IcmpErrorInfo {
    pub identifier: u16,
    pub sequence: u16,
    pub status: IcmpEchoStatus,
}

/// ICMP message types for echo request/reply operations.
///
/// This enum defines the standard ICMP type codes used for ping operations
/// across IPv4 and IPv6 protocols.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IcmpType {
    /// IPv4 Echo Request (Type 8)
    EchoRequestV4 = 8,
    /// IPv4 Echo Reply (Type 0)
    EchoReplyV4 = 0,
    /// IPv6 Echo Request (Type 128)
    EchoRequestV6 = 128,
    /// IPv6 Echo Reply (Type 129)
    EchoReplyV6 = 129,
}

impl IcmpType {
    /// Get the appropriate echo request type for the given IP address.
    ///
    /// # Arguments
    ///
    /// * `addr` - The IP address to determine the ICMP type for
    ///
    /// # Returns
    ///
    /// Returns `EchoRequestV4` for IPv4 addresses, `EchoRequestV6` for IPv6 addresses.
    pub fn echo_request_for(addr: IpAddr) -> Self {
        match addr {
            IpAddr::V4(_) => IcmpType::EchoRequestV4,
            IpAddr::V6(_) => IcmpType::EchoRequestV6,
        }
    }

    /// Get the appropriate echo reply type for the given IP address.
    ///
    /// # Arguments
    ///
    /// * `addr` - The IP address to determine the ICMP type for
    ///
    /// # Returns
    ///
    /// Returns `EchoReplyV4` for IPv4 addresses, `EchoReplyV6` for IPv6 addresses.
    pub fn echo_reply_for(addr: IpAddr) -> Self {
        match addr {
            IpAddr::V4(_) => IcmpType::EchoReplyV4,
            IpAddr::V6(_) => IcmpType::EchoReplyV6,
        }
    }

    /// Convert the ICMP type to its raw u8 value.
    ///
    /// # Returns
    ///
    /// The numeric ICMP type code as defined in the RFCs.
    pub fn as_u8(self) -> u8 {
        self as u8
    }
}

impl TryFrom<u8> for IcmpType {
    type Error = io::Error;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(IcmpType::EchoReplyV4),
            8 => Ok(IcmpType::EchoRequestV4),
            128 => Ok(IcmpType::EchoRequestV6),
            129 => Ok(IcmpType::EchoReplyV6),
            _ => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Invalid ICMP type value",
            )),
        }
    }
}

impl fmt::Display for IcmpType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IcmpType::EchoRequestV4 => write!(f, "EchoRequestV4"),
            IcmpType::EchoReplyV4 => write!(f, "EchoReplyV4"),
            IcmpType::EchoRequestV6 => write!(f, "EchoRequestV6"),
            IcmpType::EchoReplyV6 => write!(f, "EchoReplyV6"),
        }
    }
}

/// ICMP packet structure for constructing and parsing ICMP echo packets.
///
/// This struct provides functionality to create ICMP echo request packets,
/// parse incoming echo reply packets, and extract packet fields. It handles
/// the platform-specific differences in packet format and checksum calculation.
///
#[derive(Clone)]
pub struct IcmpPacket {
    data: Vec<u8>, // raw packet data
}

impl IcmpPacket {
    /// Create a new ICMP echo request packet for the specified target address.
    ///
    /// This is a convenience method that automatically selects the appropriate
    /// ICMP type (IPv4 or IPv6) based on the target address.
    ///
    /// # Arguments
    ///
    /// * `target_addr` - The destination IP address
    /// * `identifier` - A 16-bit identifier to match requests with replies
    /// * `sequence` - A 16-bit sequence number for this packet
    /// * `payload` - Optional payload data to include in the packet
    ///
    /// # Returns
    ///
    /// A new `IcmpPacket` with the appropriate checksum calculated (for IPv4).
    /// IPv6 checksums are handled by the kernel.
    pub fn new_echo_request(
        target_addr: IpAddr,
        identifier: u16,
        sequence: u16,
        payload: &[u8],
    ) -> Self {
        let icmp_type = IcmpType::echo_request_for(target_addr);
        Self::new(icmp_type, 0, identifier, sequence, payload)
    }

    /// Create a new ICMP packet with the given parameters
    pub fn new(
        icmp_type: IcmpType,
        code: u8,
        identifier: u16,
        sequence: u16,
        payload: &[u8],
    ) -> Self {
        let header_len = 8;
        let total_len = header_len + payload.len();
        let mut data = Vec::with_capacity(total_len);

        // ICMP header
        data.push(icmp_type.as_u8()); // Type
        data.push(code); // Code
        data.push(0); // Checksum (placeholder)
        data.push(0); // Checksum (placeholder)
        data.extend_from_slice(&identifier.to_be_bytes()); // Identifier
        data.extend_from_slice(&sequence.to_be_bytes()); // Sequence

        // Payload
        data.extend_from_slice(payload);

        let mut packet = IcmpPacket { data };

        // Calculate and set checksum for IPv4
        if matches!(icmp_type, IcmpType::EchoRequestV4 | IcmpType::EchoReplyV4) {
            let checksum = Self::calculate_checksum(&packet.data);
            packet.set_checksum(checksum);
        }

        packet
    }

    /// Get the packet type
    pub fn icmp_type(&self) -> u8 {
        if self.data.is_empty() {
            return 0;
        }
        self.data[0]
    }

    /// Get the packet code
    pub fn code(&self) -> u8 {
        if self.data.len() < 2 {
            return 0;
        }
        self.data[1]
    }

    #[cfg(test)]
    /// Get the checksum
    pub fn checksum(&self) -> u16 {
        if self.data.len() < 4 {
            return 0;
        }
        u16::from_be_bytes([self.data[2], self.data[3]])
    }

    /// Set the checksum
    pub fn set_checksum(&mut self, checksum: u16) {
        if self.data.len() >= 4 {
            let bytes = checksum.to_be_bytes();
            self.data[2] = bytes[0];
            self.data[3] = bytes[1];
        }
    }

    /// Get the identifier
    pub fn identifier(&self) -> u16 {
        if self.data.len() < 6 {
            return 0;
        }
        u16::from_be_bytes([self.data[4], self.data[5]])
    }

    /// Get the sequence number
    pub fn sequence(&self) -> u16 {
        if self.data.len() < 8 {
            return 0;
        }
        u16::from_be_bytes([self.data[6], self.data[7]])
    }

    /// Get the payload
    pub fn payload(&self) -> &[u8] {
        if self.data.len() <= 8 {
            return &[];
        }
        &self.data[8..]
    }

    /// Get the raw packet bytes
    pub fn as_bytes(&self) -> &[u8] {
        &self.data
    }

    #[cfg(test)]
    /// Verify the checksum (for IPv4 packets)
    fn verify_checksum(&self) -> bool {
        let icmp_type = self.icmp_type();

        // IPv6 checksums are handled by the kernel
        if icmp_type != IcmpType::EchoRequestV4.as_u8()
            && icmp_type != IcmpType::EchoReplyV4.as_u8()
        {
            return true;
        }

        // For verification, calculate checksum including the existing checksum field
        let mut sum = 0u32;
        let mut i = 0;

        // Sum all 16-bit words including the checksum field
        while i < self.data.len() {
            let word = if i + 1 < self.data.len() {
                u16::from_be_bytes([self.data[i], self.data[i + 1]])
            } else {
                u16::from_be_bytes([self.data[i], 0])
            };
            sum += word as u32;
            i += 2;
        }

        // Add carry bits
        while (sum >> 16) != 0 {
            sum = (sum & 0xFFFF) + (sum >> 16);
        }

        // For a valid packet, the sum should be 0xFFFF (all ones)
        sum as u16 == 0xFFFF
    }

    /// Parse an ICMP packet from raw bytes.
    ///
    /// # Arguments
    ///
    /// * `data` - Raw packet bytes including the ICMP header
    ///
    /// # Returns
    ///
    /// Returns `Some(IcmpPacket)` if the data contains a valid ICMP header,
    /// `None` if the data is too short (less than 8 bytes).
    pub fn parse(data: &[u8]) -> Option<IcmpPacket> {
        if data.len() < 8 {
            return None; // Minimum ICMP header size
        }

        Some(IcmpPacket {
            data: data.to_vec(),
        })
    }

    /// Parse an ICMP reply from raw socket data, handling platform-specific offsets.
    ///
    /// This method handles the platform differences in how ICMP packets are received:
    /// - On macOS, IPv4 ICMP packets include the IP header which must be skipped
    /// - On Linux, ICMP packets start immediately with the ICMP header
    /// - IPv6 packets don't include IP headers on either platform
    ///
    /// # Arguments
    ///
    /// * `data` - Raw packet data as received from the socket
    /// * `target_addr` - The target address to determine expected reply type
    ///
    /// # Returns
    ///
    /// Returns `Some(IcmpPacket)` if the data contains a valid echo reply for
    /// the target address, `None` otherwise.
    pub fn parse_reply(data: &[u8], target_addr: IpAddr) -> Option<IcmpPacket> {
        let icmp_offset = Self::ipv4_header_offset(data, target_addr)?;

        if data.len() < icmp_offset + 8 {
            return None; // Not enough data
        }

        let icmp_data = &data[icmp_offset..];

        // Check if this is an echo reply
        let expected_reply_type = IcmpType::echo_reply_for(target_addr);
        if icmp_data[0] != expected_reply_type.as_u8() {
            return None; // Not an echo reply
        }

        Self::parse(icmp_data)
    }

    /// Parse an ICMP error message (Destination Unreachable, Time Exceeded) that
    /// embeds the original echo request, and extract the identifier and sequence.
    ///
    /// # Packet structure
    ///
    /// For IPv4 ICMP errors:
    /// `[outer IP header (macOS only, variable IHL)] [ICMP error header (8)] [embedded IP header (variable IHL)] [embedded ICMP echo (8)]`
    ///
    /// For IPv6 ICMPv6 errors:
    /// `[ICMPv6 error header (8)] [embedded IPv6 header (40)] [embedded ICMPv6 echo (8)]`
    ///
    /// # Known limitations
    ///
    /// IPv6 parsing assumes no extension headers between the embedded IPv6 header
    /// and the ICMPv6 echo header. This is valid for typical echo requests.
    pub fn parse_error_reply(data: &[u8], target_addr: IpAddr) -> Option<IcmpErrorInfo> {
        let outer_offset = Self::ipv4_header_offset(data, target_addr)?;

        // Need at least the ICMP error header (8 bytes)
        if data.len() < outer_offset + 8 {
            return None;
        }

        let icmp_data = &data[outer_offset..];
        let icmp_type = icmp_data[0];

        // Determine status from ICMP error type
        let status = if target_addr.is_ipv4() {
            match icmp_type {
                ICMPV4_DEST_UNREACHABLE => IcmpEchoStatus::Unreachable,
                ICMPV4_TIME_EXCEEDED => IcmpEchoStatus::TimedOut,
                _ => return None,
            }
        } else {
            match icmp_type {
                ICMPV6_DEST_UNREACHABLE => IcmpEchoStatus::Unreachable,
                ICMPV6_TIME_EXCEEDED => IcmpEchoStatus::TimedOut,
                _ => return None,
            }
        };

        // Skip the 8-byte ICMP error header to reach the embedded original packet
        let embedded = &icmp_data[8..];

        if target_addr.is_ipv4() {
            // Embedded IPv4 packet
            if embedded.is_empty() {
                return None;
            }
            let version = (embedded[0] >> 4) & 0x0F;
            if version != 4 {
                return None;
            }
            let embedded_ihl = (embedded[0] & 0x0F) as usize * 4;
            if embedded_ihl < 20 {
                return None;
            }
            // Need embedded IP header + 8 bytes of embedded ICMP echo header
            if embedded.len() < embedded_ihl + 8 {
                return None;
            }
            // Verify protocol is ICMP (byte 9 of IP header)
            if embedded[9] != IP_PROTO_ICMP {
                return None;
            }
            let embedded_icmp = &embedded[embedded_ihl..];
            // Verify embedded ICMP type is Echo Request
            if embedded_icmp[0] != ICMPV4_ECHO_REQUEST {
                return None;
            }
            let identifier = u16::from_be_bytes([embedded_icmp[4], embedded_icmp[5]]);
            let sequence = u16::from_be_bytes([embedded_icmp[6], embedded_icmp[7]]);
            Some(IcmpErrorInfo {
                identifier,
                sequence,
                status,
            })
        } else {
            // Embedded IPv6 packet
            if embedded.len() < IPV6_HEADER_LEN + 8 {
                return None;
            }
            let version = (embedded[0] >> 4) & 0x0F;
            if version != 6 {
                return None;
            }
            // Next Header field at byte 6
            if embedded[6] != IP_PROTO_ICMPV6 {
                return None;
            }
            let embedded_icmpv6 = &embedded[IPV6_HEADER_LEN..];
            // Verify embedded ICMPv6 type is Echo Request
            if embedded_icmpv6[0] != ICMPV6_ECHO_REQUEST {
                return None;
            }
            let identifier = u16::from_be_bytes([embedded_icmpv6[4], embedded_icmpv6[5]]);
            let sequence = u16::from_be_bytes([embedded_icmpv6[6], embedded_icmpv6[7]]);
            Some(IcmpErrorInfo {
                identifier,
                sequence,
                status,
            })
        }
    }

    /// Returns the platform-specific outer IP header offset for the given data.
    ///
    /// On macOS, IPv4 DGRAM sockets include the IP header; the IHL is read from
    /// the first nibble. On Linux and for IPv6, the offset is always 0.
    fn ipv4_header_offset(data: &[u8], target_addr: IpAddr) -> Option<usize> {
        if cfg!(target_os = "macos") && target_addr.is_ipv4() {
            if data.is_empty() {
                return None;
            }
            let ihl = (data[0] & 0x0F) as usize * 4;
            if ihl < 20 {
                return None;
            }
            Some(ihl)
        } else {
            Some(0)
        }
    }

    /// Calculate Internet checksum (RFC 1071)
    /// Returns the 16-bit one's complement checksum
    fn calculate_checksum(data: &[u8]) -> u16 {
        let mut sum = 0u32;
        let mut i = 0;

        // Sum 16-bit words, skipping checksum field (bytes 2-3)
        while i < data.len() {
            if i == 2 {
                i += 2; // Skip checksum field
                continue;
            }

            let word = if i + 1 < data.len() {
                u16::from_be_bytes([data[i], data[i + 1]])
            } else {
                // Odd number of bytes, pad with zero
                u16::from_be_bytes([data[i], 0])
            };

            sum += word as u32;
            i += 2;
        }

        // Add carry bits
        while (sum >> 16) != 0 {
            sum = (sum & 0xFFFF) + (sum >> 16);
        }

        // One's complement
        !sum as u16
    }
}

impl fmt::Debug for IcmpPacket {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match IcmpType::try_from(self.icmp_type()).ok() {
            Some(IcmpType::EchoRequestV4) | Some(IcmpType::EchoReplyV4) => f
                .debug_struct("IcmpPacket")
                .field("icmp_type", &self.icmp_type())
                .field("code", &self.code())
                .field("identifier", &self.identifier())
                .field("sequence", &self.sequence())
                .field("payload", &self.payload())
                .finish(),
            Some(IcmpType::EchoRequestV6) | Some(IcmpType::EchoReplyV6) => f
                .debug_struct("IcmpPacket")
                .field("icmp_type", &self.icmp_type())
                .field("code", &self.code())
                .finish(),
            None => f
                .debug_struct("IcmpPacket")
                .field("icmp_type", &self.icmp_type())
                .finish(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv4Addr;

    #[test]
    fn test_icmp_type_conversions() {
        assert_eq!(IcmpType::EchoRequestV4.as_u8(), 8);
        assert_eq!(IcmpType::EchoReplyV4.as_u8(), 0);
        assert_eq!(IcmpType::EchoRequestV6.as_u8(), 128);
        assert_eq!(IcmpType::EchoReplyV6.as_u8(), 129);

        assert_eq!(IcmpType::try_from(8).unwrap(), IcmpType::EchoRequestV4);
        assert_eq!(IcmpType::try_from(0).unwrap(), IcmpType::EchoReplyV4);
        assert_eq!(IcmpType::try_from(128).unwrap(), IcmpType::EchoRequestV6);
        assert_eq!(IcmpType::try_from(129).unwrap(), IcmpType::EchoReplyV6);

        // Test invalid values return errors
        assert!(IcmpType::try_from(1).is_err());
        assert!(IcmpType::try_from(255).is_err());
        assert!(IcmpType::try_from(100).is_err());

        let error = IcmpType::try_from(42).unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert_eq!(error.to_string(), "Invalid ICMP type value");
    }

    #[test]
    fn test_icmp_type_for_addresses() {
        let ipv4_addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let ipv6_addr = IpAddr::V6("::1".parse().unwrap());

        assert_eq!(
            IcmpType::echo_request_for(ipv4_addr),
            IcmpType::EchoRequestV4
        );
        assert_eq!(
            IcmpType::echo_request_for(ipv6_addr),
            IcmpType::EchoRequestV6
        );
        assert_eq!(IcmpType::echo_reply_for(ipv4_addr), IcmpType::EchoReplyV4);
        assert_eq!(IcmpType::echo_reply_for(ipv6_addr), IcmpType::EchoReplyV6);
    }

    #[test]
    fn test_icmp_packet_creation() {
        let target = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let payload = [1, 2, 3, 4, 5, 6, 7, 8];

        let packet = IcmpPacket::new_echo_request(target, 0x1234, 0x5678, &payload);

        assert_eq!(packet.icmp_type(), IcmpType::EchoRequestV4.as_u8());
        assert_eq!(packet.code(), 0);
        assert_eq!(packet.identifier(), 0x1234);
        assert_eq!(packet.sequence(), 0x5678);
        assert_eq!(packet.payload(), &payload);
        assert_eq!(packet.data.len(), 8 + payload.len());
    }

    #[test]
    fn test_icmp_packet_parsing() {
        // Create a known packet
        let original_payload = [0xAA, 0xBB, 0xCC, 0xDD];
        let target = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
        let packet = IcmpPacket::new_echo_request(target, 0x1111, 0x2222, &original_payload);

        // Parse it back
        let parsed = IcmpPacket::parse(&packet.data).unwrap();

        assert_eq!(parsed.icmp_type(), IcmpType::EchoRequestV4.as_u8());
        assert_eq!(parsed.identifier(), 0x1111);
        assert_eq!(parsed.sequence(), 0x2222);
        assert_eq!(parsed.payload(), &original_payload);
    }

    #[test]
    fn test_checksum_calculation() {
        // Test with a known ICMP packet
        let target = IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8));
        let payload = [0; 8]; // 8 zero bytes
        let packet = IcmpPacket::new_echo_request(target, 0x0001, 0x0001, &payload);

        // Verify checksum is calculated
        assert_ne!(packet.checksum(), 0);

        // Verify checksum validation
        assert!(packet.verify_checksum());
    }

    #[test]
    fn test_ipv6_packet_no_checksum() {
        let target = IpAddr::V6("::1".parse().unwrap());
        let payload = [1, 2, 3, 4];
        let packet = IcmpPacket::new_echo_request(target, 0x1234, 0x5678, &payload);

        // IPv6 packets should have checksum 0 (handled by kernel)
        assert_eq!(packet.checksum(), 0);
        // But verify_checksum should still return true
        assert!(packet.verify_checksum());
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_parse_icmp_reply_macos() {
        let mut ip_header = [0u8; 20];
        ip_header[0] = 0x45; // version=4, IHL=5 (20 bytes)
        let icmp_data = [
            0, // Echo Reply
            0, // Code
            0, 0, // Checksum
            0x12, 0x34, // Identifier
            0x56, 0x78, // Sequence
            0xAA, 0xBB, 0xCC, 0xDD, // Payload
        ];

        let mut full_packet = Vec::new();
        full_packet.extend_from_slice(&ip_header);
        full_packet.extend_from_slice(&icmp_data);

        let target = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let parsed = IcmpPacket::parse_reply(&full_packet, target).unwrap();

        assert_eq!(parsed.icmp_type(), IcmpType::EchoReplyV4.as_u8());
        assert_eq!(parsed.identifier(), 0x1234);
        assert_eq!(parsed.sequence(), 0x5678);
        assert_eq!(parsed.payload(), &[0xAA, 0xBB, 0xCC, 0xDD]);
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_parse_icmp_reply_linux() {
        let icmp_data = [
            0, // Echo Reply
            0, // Code
            0, 0, // Checksum
            0x12, 0x34, // Identifier
            0x56, 0x78, // Sequence
            0xAA, 0xBB, 0xCC, 0xDD, // Payload
        ];

        let target = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let parsed = IcmpPacket::parse_reply(&icmp_data, target).unwrap();

        assert_eq!(parsed.icmp_type(), IcmpType::EchoReplyV4.as_u8());
        assert_eq!(parsed.identifier(), 0x1234);
        assert_eq!(parsed.sequence(), 0x5678);
        assert_eq!(parsed.payload(), &[0xAA, 0xBB, 0xCC, 0xDD]);
    }

    #[test]
    fn test_parse_icmp6_reply() {
        let icmp6_data = [
            129, // ICMPv6 Echo Reply
            0,   // Code
            0, 0, // Checksum (handled by kernel for IPv6)
            0x12, 0x34, // Identifier
            0x56, 0x78, // Sequence
            0xAA, 0xBB, 0xCC, 0xDD, // Payload
        ];

        let target = IpAddr::V6("::1".parse().unwrap());
        let parsed = IcmpPacket::parse_reply(&icmp6_data, target).unwrap();

        assert_eq!(parsed.icmp_type(), IcmpType::EchoReplyV6.as_u8());
        assert_eq!(parsed.code(), 0);
        assert_eq!(parsed.identifier(), 0x1234);
        assert_eq!(parsed.sequence(), 0x5678);
        assert_eq!(parsed.payload(), &[0xAA, 0xBB, 0xCC, 0xDD]);

        // IPv6 packets don't use offset (no IP header stripping needed)
        assert_eq!(parsed.checksum(), 0); // Checksum handled by kernel
    }

    #[test]
    fn test_invalid_packets() {
        // Too short
        assert!(IcmpPacket::parse(&[1, 2, 3]).is_none());

        // Wrong type in reply parsing
        let wrong_type_packet = [
            8, // Echo Request (not Reply)
            0, // Code
            0, 0, // Checksum
            0, 0, // Identifier
            0, 0, // Sequence
        ];
        let target = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        assert!(IcmpPacket::parse_reply(&wrong_type_packet, target).is_none());
    }

    /// Helper: build a minimal IPv4 header (20 bytes, IHL=5).
    fn make_ipv4_header(protocol: u8) -> Vec<u8> {
        let mut hdr = vec![0u8; 20];
        hdr[0] = 0x45; // version 4, IHL 5 (20 bytes)
        hdr[9] = protocol;
        hdr
    }

    /// Helper: build an ICMP echo request header (8 bytes) with the given id/seq.
    fn make_echo_request_v4(identifier: u16, sequence: u16) -> Vec<u8> {
        let mut pkt = vec![0u8; 8];
        pkt[0] = ICMPV4_ECHO_REQUEST; // type
        pkt[4..6].copy_from_slice(&identifier.to_be_bytes());
        pkt[6..8].copy_from_slice(&sequence.to_be_bytes());
        pkt
    }

    /// Helper: build an ICMPv6 echo request header (8 bytes) with the given id/seq.
    fn make_echo_request_v6(identifier: u16, sequence: u16) -> Vec<u8> {
        let mut pkt = vec![0u8; 8];
        pkt[0] = ICMPV6_ECHO_REQUEST; // type
        pkt[4..6].copy_from_slice(&identifier.to_be_bytes());
        pkt[6..8].copy_from_slice(&sequence.to_be_bytes());
        pkt
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_parse_error_reply_v4_dest_unreachable_linux() {
        let target = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));

        // Build: [ICMP Dest Unreachable header (8)] [embedded IPv4 (20)] [embedded echo (8)]
        let mut packet = Vec::new();
        // ICMP error header: type=3, code=1, checksum=0, unused=0
        packet.extend_from_slice(&[ICMPV4_DEST_UNREACHABLE, 1, 0, 0, 0, 0, 0, 0]);
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        packet.extend_from_slice(&make_echo_request_v4(0xABCD, 0x0042));

        let info = IcmpPacket::parse_error_reply(&packet, target).unwrap();
        assert_eq!(info.identifier, 0xABCD);
        assert_eq!(info.sequence, 0x0042);
        assert_eq!(info.status, IcmpEchoStatus::Unreachable);
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_parse_error_reply_v4_time_exceeded_linux() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        let mut packet = Vec::new();
        // ICMP error header: type=11 (Time Exceeded), code=0
        packet.extend_from_slice(&[ICMPV4_TIME_EXCEEDED, 0, 0, 0, 0, 0, 0, 0]);
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        packet.extend_from_slice(&make_echo_request_v4(0x1234, 0x0007));

        let info = IcmpPacket::parse_error_reply(&packet, target).unwrap();
        assert_eq!(info.identifier, 0x1234);
        assert_eq!(info.sequence, 0x0007);
        assert_eq!(info.status, IcmpEchoStatus::TimedOut);
    }

    #[test]
    fn test_parse_error_reply_v6_dest_unreachable() {
        let target: IpAddr = "2001:db8::1".parse().unwrap();

        // Build: [ICMPv6 error header (8)] [embedded IPv6 (40)] [embedded echo (8)]
        let mut packet = Vec::new();
        // ICMPv6 error header: type=1 (Dest Unreachable), code=0
        packet.extend_from_slice(&[ICMPV6_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0]);
        // Embedded IPv6 header (40 bytes)
        let mut ipv6_hdr = vec![0u8; 40];
        ipv6_hdr[0] = 0x60; // version 6
        ipv6_hdr[6] = IP_PROTO_ICMPV6; // Next Header
        packet.extend_from_slice(&ipv6_hdr);
        packet.extend_from_slice(&make_echo_request_v6(0x5678, 0x0003));

        let info = IcmpPacket::parse_error_reply(&packet, target).unwrap();
        assert_eq!(info.identifier, 0x5678);
        assert_eq!(info.sequence, 0x0003);
        assert_eq!(info.status, IcmpEchoStatus::Unreachable);
    }

    #[test]
    fn test_parse_error_reply_v6_time_exceeded() {
        let target: IpAddr = "fe80::1".parse().unwrap();

        let mut packet = Vec::new();
        // ICMPv6 error header: type=3 (Time Exceeded), code=0
        packet.extend_from_slice(&[ICMPV6_TIME_EXCEEDED, 0, 0, 0, 0, 0, 0, 0]);
        let mut ipv6_hdr = vec![0u8; 40];
        ipv6_hdr[0] = 0x60;
        ipv6_hdr[6] = IP_PROTO_ICMPV6;
        packet.extend_from_slice(&ipv6_hdr);
        packet.extend_from_slice(&make_echo_request_v6(0x9999, 0x000A));

        let info = IcmpPacket::parse_error_reply(&packet, target).unwrap();
        assert_eq!(info.identifier, 0x9999);
        assert_eq!(info.sequence, 0x000A);
        assert_eq!(info.status, IcmpEchoStatus::TimedOut);
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_parse_error_reply_wrong_protocol_linux() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        let mut packet = Vec::new();
        packet.extend_from_slice(&[ICMPV4_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0]);
        // Embedded IP header with protocol=17 (UDP), not ICMP
        packet.extend_from_slice(&make_ipv4_header(17));
        packet.extend_from_slice(&make_echo_request_v4(0x1234, 0x0001));

        assert!(IcmpPacket::parse_error_reply(&packet, target).is_none());
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_parse_error_reply_wrong_embedded_type_linux() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        let mut packet = Vec::new();
        packet.extend_from_slice(&[ICMPV4_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0]);
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        // Embedded ICMP with type=0 (Echo Reply) instead of Echo Request
        let mut echo = make_echo_request_v4(0x1234, 0x0001);
        echo[0] = 0; // Echo Reply
        packet.extend_from_slice(&echo);

        assert!(IcmpPacket::parse_error_reply(&packet, target).is_none());
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_parse_error_reply_truncated_v4_linux() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        // Too short — only the ICMP error header, no embedded packet
        let packet = [ICMPV4_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0];
        assert!(IcmpPacket::parse_error_reply(&packet, target).is_none());

        // Truncated embedded IP header (only 10 bytes instead of 20+)
        let mut packet2 = Vec::new();
        packet2.extend_from_slice(&[ICMPV4_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0]);
        packet2.extend_from_slice(&[0x45, 0, 0, 0, 0, 0, 0, 0, 0, IP_PROTO_ICMP]);
        assert!(IcmpPacket::parse_error_reply(&packet2, target).is_none());
    }

    #[test]
    fn test_parse_error_reply_truncated_v6() {
        let target_v6: IpAddr = "::1".parse().unwrap();
        let mut packet = Vec::new();
        packet.extend_from_slice(&[ICMPV6_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0]);
        packet.extend_from_slice(&[0x60; 20]); // Only 20 bytes, need 40+8
        assert!(IcmpPacket::parse_error_reply(&packet, target_v6).is_none());
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_parse_error_reply_not_an_error_linux() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        // ICMP Echo Reply (type=0) is not an error message
        let mut packet = Vec::new();
        packet.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]); // type=0 (Echo Reply)
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        packet.extend_from_slice(&make_echo_request_v4(0x1234, 0x0001));

        assert!(IcmpPacket::parse_error_reply(&packet, target).is_none());
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_parse_error_reply_macos_with_outer_ip_header() {
        let target = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));

        // On macOS IPv4, the raw socket includes the outer IP header
        let mut packet = Vec::new();
        // Outer IP header (20 bytes, IHL=5)
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        // ICMP Dest Unreachable header
        packet.extend_from_slice(&[ICMPV4_DEST_UNREACHABLE, 1, 0, 0, 0, 0, 0, 0]);
        // Embedded IP header
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        // Embedded echo request
        packet.extend_from_slice(&make_echo_request_v4(0xBEEF, 0x0010));

        let info = IcmpPacket::parse_error_reply(&packet, target).unwrap();
        assert_eq!(info.identifier, 0xBEEF);
        assert_eq!(info.sequence, 0x0010);
        assert_eq!(info.status, IcmpEchoStatus::Unreachable);
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_parse_error_reply_v4_time_exceeded_macos() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        let mut packet = Vec::new();
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP)); // outer IP header
        packet.extend_from_slice(&[ICMPV4_TIME_EXCEEDED, 0, 0, 0, 0, 0, 0, 0]);
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        packet.extend_from_slice(&make_echo_request_v4(0x1234, 0x0007));

        let info = IcmpPacket::parse_error_reply(&packet, target).unwrap();
        assert_eq!(info.identifier, 0x1234);
        assert_eq!(info.sequence, 0x0007);
        assert_eq!(info.status, IcmpEchoStatus::TimedOut);
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_parse_error_reply_wrong_protocol_macos() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        let mut packet = Vec::new();
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP)); // outer IP header
        packet.extend_from_slice(&[ICMPV4_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0]);
        packet.extend_from_slice(&make_ipv4_header(17)); // embedded: UDP, not ICMP
        packet.extend_from_slice(&make_echo_request_v4(0x1234, 0x0001));

        assert!(IcmpPacket::parse_error_reply(&packet, target).is_none());
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_parse_error_reply_wrong_embedded_type_macos() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        let mut packet = Vec::new();
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP)); // outer IP header
        packet.extend_from_slice(&[ICMPV4_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0]);
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        let mut echo = make_echo_request_v4(0x1234, 0x0001);
        echo[0] = 0; // Echo Reply instead of Echo Request
        packet.extend_from_slice(&echo);

        assert!(IcmpPacket::parse_error_reply(&packet, target).is_none());
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_parse_error_reply_truncated_v4_macos() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        // Outer IP header only — no ICMP error header
        let packet = make_ipv4_header(IP_PROTO_ICMP);
        assert!(IcmpPacket::parse_error_reply(&packet, target).is_none());

        // Outer IP header + ICMP error header but no embedded packet
        let mut packet2 = Vec::new();
        packet2.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        packet2.extend_from_slice(&[ICMPV4_DEST_UNREACHABLE, 0, 0, 0, 0, 0, 0, 0]);
        assert!(IcmpPacket::parse_error_reply(&packet2, target).is_none());
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_parse_error_reply_not_an_error_macos() {
        let target = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        let mut packet = Vec::new();
        // outer IP header
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        // type=0 (Echo Reply) — not an error message
        packet.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
        packet.extend_from_slice(&make_ipv4_header(IP_PROTO_ICMP));
        packet.extend_from_slice(&make_echo_request_v4(0x1234, 0x0001));

        assert!(IcmpPacket::parse_error_reply(&packet, target).is_none());
    }
}