抓包分析器 Day 4:IPv4 首部解码与校验和 Checksum 计算

今天是抓包分析器(PacketAnalyzer CLI)实战开发的第四天。
昨天我们成功从以太网数据帧(Ethernet Frame II)中剥离出了链路层头部,并根据 EtherType == 0x0800 将网络层载荷分流到了 IPv4 解析模块。在 TCP/IP 协议栈中,IPv4 报文首部承载着最核心的路由与传输控制信息。
今天我们的任务是:在 packet-core 模块中实现一个工业级的 IPv4 报文首部解析器,不仅能够精准提取源 IP、目的 IP、协议号(Protocol)、生存时间(TTL)、分片标志(Flags/Offset),还要在纯 Rust 中实现高效的 网际校验和(Internet Checksum)校验算法,用于检测传输中发生比特翻转的损坏报文。
1. IPv4 首部二进制格式深度剖析
标准 IPv4 报文首部最小长度为 20 字节(若包含可选 Options 字段则可达 60 字节):
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| IHL |Type of Service| Total Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identification |Flags| Fragment Offset |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Time to Live | Protocol | Header Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- Version (4 bits):必须为 4;
- IHL (Internet Header Length, 4 bits):首部长度(以 32 位/4 字节为单位),最小值为 5(即 20 字节);
- Total Length (16 bits):整个 IP 报文(首部 + 载荷)的总字节数;
- Flags (3 bits):保留位、DF(Don't Fragment 不分片)、MF(More Fragments 更多分片);
- TTL (8 bits):每经过一个路由器减 1,防死循环;
- Protocol (8 bits):上层协议代码(
6代表 TCP,17代表 UDP,1代表 ICMP); - Header Checksum (16 bits):首部 16 位反码求和的校验和。
2. 16 位反码求和算法(Internet Checksum)的 Rust 实现
根据 RFC 1071 规范,IP 首部校验和的计算算法如下:
- 将首部按 16 位(2 字节)大端序切分成一系列整数并相加;
- 如果产生高 16 位的进位(Carry),将进位回折累加到低 16 位中;
- 对最终的累加和取反码(Not)。如果报文未损坏,包含原校验和在内的全首部校验和结果必须为
0x0000或0xFFFF。
在 crates/packet-core/src/checksum.rs 中:
// crates/packet-core/src/checksum.rs
pub fn compute_ip_checksum(header_bytes: &[u8]) -> u16 {
let mut sum: u32 = 0;
let mut chunks = header_bytes.chunks_exact(2);
// 两个字节一组进行累加
for chunk in &mut chunks {
let word = u16::from_be_bytes([chunk[0], chunk[1]]);
sum += word as u32;
}
// 若首部长度为奇数(虽然标准 IP 首部按 4 字节对齐,做防御性处理)
let remainder = chunks.remainder();
if !remainder.is_empty() {
let word = (remainder[0] as u32) << 8;
sum += word;
}
// 将高 16 位的进位折叠累加到低 16 位
while (sum >> 16) > 0 {
sum = (sum & 0xFFFF) + (sum >> 16);
}
// 取反码
!(sum as u16)
}
/// 验证首部校验和是否正确
pub fn verify_ip_checksum(header_bytes: &[u8]) -> bool {
compute_ip_checksum(header_bytes) == 0
}
3. 实现 IPv4 首部强类型解码器
在 crates/packet-core/src/ipv4.rs 中:
// crates/packet-core/src/ipv4.rs
use crate::checksum::verify_ip_checksum;
use crate::error::{IpError, ParseError};
use std::net::Ipv4Addr;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IpProtocol {
Tcp,
Udp,
Icmp,
Other(u8),
}
impl From<u8> for IpProtocol {
fn from(val: u8) -> Self {
match val {
1 => IpProtocol::Icmp,
6 => IpProtocol::Tcp,
17 => IpProtocol::Udp,
other => IpProtocol::Other(other),
}
}
}
#[derive(Debug, Clone)]
pub struct Ipv4Header {
pub version: u8,
pub ihl_bytes: usize,
pub dscp_ecn: u8,
pub total_length: u16,
pub identification: u16,
pub dont_fragment: bool,
pub more_fragments: bool,
pub fragment_offset: u16,
pub ttl: u8,
pub protocol: IpProtocol,
pub checksum: u16,
pub src_ip: Ipv4Addr,
pub dst_ip: Ipv4Addr,
pub checksum_valid: bool,
}
pub struct Ipv4PacketView<'a> {
pub header: Ipv4Header,
pub payload: &'a [u8],
}
impl<'a> Ipv4PacketView<'a> {
pub fn parse(raw_ip_bytes: &'a [u8]) -> Result<Self, ParseError> {
if raw_ip_bytes.len() < 20 {
return Err(ParseError::UndersizedFrame);
}
let ver_ihl = raw_ip_bytes[0];
let version = ver_ihl >> 4;
let ihl = ver_ihl & 0x0F;
if version != 4 {
return Err(IpError::UnsupportedVersion(version).into());
}
let ihl_bytes = (ihl * 4) as usize;
if ihl_bytes < 20 || raw_ip_bytes.len() < ihl_bytes {
return Err(IpError::InvalidIhl(ihl_bytes).into());
}
let dscp_ecn = raw_ip_bytes[1];
let total_length = u16::from_be_bytes([raw_ip_bytes[2], raw_ip_bytes[3]]);
let identification = u16::from_be_bytes([raw_ip_bytes[4], raw_ip_bytes[5]]);
let flags_offset = u16::from_be_bytes([raw_ip_bytes[6], raw_ip_bytes[7]]);
let dont_fragment = (flags_offset & 0x4000) != 0;
let more_fragments = (flags_offset & 0x2000) != 0;
let fragment_offset = flags_offset & 0x1FFF;
let ttl = raw_ip_bytes[8];
let protocol = IpProtocol::from(raw_ip_bytes[9]);
let checksum = u16::from_be_bytes([raw_ip_bytes[10], raw_ip_bytes[11]]);
let src_ip = Ipv4Addr::new(raw_ip_bytes[12], raw_ip_bytes[13], raw_ip_bytes[14], raw_ip_bytes[15]);
let dst_ip = Ipv4Addr::new(raw_ip_bytes[16], raw_ip_bytes[17], raw_ip_bytes[18], raw_ip_bytes[19]);
// 校验 Checksum 是否损坏
let checksum_valid = verify_ip_checksum(&raw_ip_bytes[0..ihl_bytes]);
let header = Ipv4Header {
version,
ihl_bytes,
dscp_ecn,
total_length,
identification,
dont_fragment,
more_fragments,
fragment_offset,
ttl,
protocol,
checksum,
src_ip,
dst_ip,
checksum_valid,
};
// 提取 IP 载荷(例如传输层 TCP/UDP 报文)
let payload_end = (total_length as usize).min(raw_ip_bytes.len());
let payload = &raw_ip_bytes[ihl_bytes..payload_end];
Ok(Self { header, payload })
}
}
4. 单元测试覆盖
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_ipv4_packet() {
// 标准 20 字节 IPv4 首部(源 192.168.1.100 -> 目的 8.8.8.8,TCP 协议,TTL=64)
let raw_ip = vec![
0x45, 0x00, 0x00, 0x28, // Ver/IHL, ToS, TotalLen=40
0x1C, 0x2D, 0x40, 0x00, // ID, Flags(DF), FragOffset=0
0x40, 0x06, 0xE2, 0x56, // TTL=64, Proto=6(TCP), Valid Checksum
0xC0, 0xA8, 0x01, 0x64, // 192.168.1.100
0x08, 0x08, 0x08, 0x08, // 8.8.8.8
// 接下来 20 字节假载荷
0x00, 0x50, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x50, 0x02, 0x20, 0x00,
0x00, 0x00, 0x00, 0x00,
];
let parsed = Ipv4PacketView::parse(&raw_ip).expect("解析 IPv4 失败");
assert_eq!(parsed.header.version, 4);
assert_eq!(parsed.header.src_ip.to_string(), "192.168.1.100");
assert_eq!(parsed.header.dst_ip.to_string(), "8.8.8.8");
assert_eq!(parsed.header.protocol, IpProtocol::Tcp);
assert_eq!(parsed.header.ttl, 64);
assert!(parsed.header.dont_fragment);
assert!(parsed.header.checksum_valid);
assert_eq!(parsed.payload.len(), 20);
}
}
总结与明日规划
今天顺利打通了网络层的核心解析能力:
- 严格遵循 RFC 1071 实现了 16 位反码求和算法;
- 支持 IHL 变长首部与 Options 选项自适应;
- 零拷贝返回 IP 载荷切片。
明天(Day 5),我们将正式向传输层进发——实现 TCP 报文首部解码、六大控制标志位(SYN/ACK/FIN/RST/PSH/URG)提取与滑动窗口计算!
636



被折叠的 条评论
为什么被折叠?



