IP Header Checksum计算c实现

关于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:发送前需要将结果转换为网络序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章