c - IP校验和计算

标签 c ip checksum

我正在尝试计算一个 ip 地址 header (没有选项)的校验和,遵循以下算法:将 header 分成 16 位字,对所有字求和,对结果应用 NOT 运算符以获得校验和,但是我仍然得到错误的结果,用 wireshark 嗅探数据包我可以看到它们是错误的,例如,这是我的方法:

void compute_ip_checksum(struct ip_hdr* ip){
unsigned short* begin = (unsigned short*)ip;
unsigned short* end = begin + (IP_NOPT_HEADER_LENGTH / 2);
unsigned short checksum = 0;

ip->checksum = 0;
for (; begin != end; begin++){
    checksum += *begin;
}

ip->checksum = htons(~checksum);
}

我构建的 ip header 是:

ip.version_and_length = (IPV4 << 4) | (IP_NOPT_HEADER_LENGTH/4);
ip.type_of_service = 0;
ip.total_length = htons(IP_NOPT_HEADER_LENGTH + TCP_NOPT_HEADER_LENGTH);
ip.frag_id = 0;
ip.flags_and_frag_offset = htons(DONT_FRAGMENT << 13);
ip.time_to_live = 128;
ip.protocol = TCP_PAYLOAD;
ip.src_ip = inet_addr("1.1.1.1");
ip.dst_ip = inet_addr("1.1.1.2");

因为我将所有值都转换为网络字节顺序,所以我没有在校验和中做任何转换,只有在 NOT 操作之后,因为我几乎可以肯定我的窗口是 LITTLEENDIAN,如果那是在这种情况下,结果将放在这个字节顺序中。我的函数的结果是:0x7a17 并且此 header 的 wireshark 结果是 0x7917。有人可以解释这里出了什么问题吗?我的引用资料是:RFC 791How to Calculate IpHeader Checksum

最佳答案

因此在阅读此链接后:wikipedia我可以看出校验和比预期的要复杂一些,现在这是适合我的代码:

void compute_ip_checksum(struct ip_hdr* ip, struct ip_options* opt){
unsigned short* begin = (unsigned short*)ip;
unsigned short* end = begin + IP_NOPT_HEADER_LENGTH / 2;
unsigned int checksum = 0, first_half, second_half;

ip->checksum = 0;
for (; begin != end; begin++){
    checksum += *begin;
}

first_half = (unsigned short)(checksum >> 16);
while (first_half){
    second_half = (unsigned short)((checksum << 16) >> 16);
    checksum = first_half + second_half;
    first_half = (unsigned short)(checksum >> 16);
}

ip->checksum = ~checksum;
}

如你所见,NOT操作后不需要转换,我把进位计算放在一个循环中,因为我不知道我要执行多少次这一步,我认为在我的如果不超过一个。

关于c - IP校验和计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32750903/

相关文章:

用于分布式计算的 C++ 与 C

c - 无法理解我的 C 程序的正确输出

objective-c - C 或 Objective-C 等效于 Java 的 Integer.toOctalString()?

c - 将值从 SQLite 数据库导出到 CSV

iphone - 调整UIImagePickerController视频采集界面大小

php - 如何知道IP是否是外部IP?

Javascript - IP地址显示国家

忽略元数据的Python文件校验和

java - 使用字节进行数学运算

serial-port - 字节流中数据包的识别