关于IP Header Checksum的计算在RFC791中有比较完整的描叙,
Header Checksum: 16 bits
A checksum on the header only. Since some header fields change
(e.g., time to live), this is recomputed and verified at each point
that the internet header is processed.
The checksum algorithm is:
The checksum field is the 16 bit one's complement of the one's
complement sum of all 16 bit words in the header. For purposes of
computing the checksum, the value of the checksum field is zero.
This is a simple to compute checksum and experimental evidence
indicates it is adequate, but it is provisional and may be replaced
by a CRC procedure, depending on further experience.
大致意义如下:
Checksum只是和IP头相关的,当头中的数据被改变时才需要重新计算Checksum。
Checksum是IP头中,第0位开始所有16位数据的和。在计算前需要将Checksum本身的值设置为0。
代码:
_Int16 GetIpCheckSum( Byte *ptr, int size)
{
int cksum = 0;
int index = 0;
*(ptr + 10) = 0;
*(ptr + 11) = 0;
if(size % 2 != 0)
return 0;
while(index < size)
{
cksum += *(ptr + index + 1);
cksum += *(ptr + index) << 8;
index += 2;
}
while(cksum > 0xffff)
{
cksum = (cksum >> 16) + (cksum & 0xffff);
}
return ~cksum;
}ps:发送前需要将结果转换为网络序

本文详细介绍了IP头部校验和(Checksum)的计算方法及其重要性。校验和仅与IP头部相关,当头部数据发生变化时需重新计算。文章通过示例代码展示了具体的计算过程,包括如何将校验和字段置零进行计算。
2558

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



