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:發送前需要將結果轉換爲網絡序

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