IP Header Checksum計算c實現

來源:互聯網
上載者:User

關於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:發送前需要將結果轉換為網路序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.