Skip to content

Commit

Permalink
feat(net): add IPv4 header checksum
Browse files Browse the repository at this point in the history
  • Loading branch information
fujiapple852 committed Dec 29, 2023
1 parent f0b1067 commit c65a57e
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/tracing/packet/checksum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
use crate::tracing::packet::IpProtocol;
use std::net::{Ipv4Addr, Ipv6Addr};

/// Calculate the checksum for an `Ipv4` header.
#[must_use]
pub fn ipv4_header_checksum(data: &[u8]) -> u16 {
checksum(data, 5)
}

/// Calculate the checksum for an `Ipv4` `ICMP` packet.
#[must_use]
pub fn icmp_ipv4_checksum(data: &[u8]) -> u16 {
Expand Down Expand Up @@ -113,6 +119,7 @@ fn finalize_checksum(mut sum: u32) -> u16 {
#[cfg(test)]
mod tests {
use super::*;
use hex_literal::hex;
use std::str::FromStr;

#[test]
Expand Down Expand Up @@ -166,4 +173,10 @@ mod tests {
];
assert_eq!(61454, udp_ipv6_checksum(&bytes, src_addr, dest_addr));
}

#[test]
fn test_ipv4_header_checksum() {
let bytes = hex!("45 00 0f fc 38 c0 00 00 40 01 2e 3b 0a 00 00 02 0a 00 00 01");
assert_eq!(0x1e3f, ipv4_header_checksum(&bytes));
}
}

0 comments on commit c65a57e

Please sign in to comment.