unsigned short /* this function generates header checksums */
csum (unsigned short *buf, int nwords)
{
unsigned long sum;
for (sum = 0; nwords > 0; nwords--) // add words(16bits) together
{
sum += *buf++;
}
sum = (sum >> 16) + (sum & 0xffff); //add carry over
sum += (sum >> 16); //MY question: what exactly does this step do??? add possible left-over
//byte? But hasn't it already been added in the loop (if
//any)?
return ((unsigned short) ~sum);
}
- 我nwords承擔16位的字的數量問題,而不是8位字節(如果有奇數個字節,nword四捨五入到下一個大),是正確的嗎?說ip_hdr總共有27個字節,那麼nword將是14而不是13,對不對?
- 總和=(總和>> 16)+(總和& 0xffff)是加進位16位補全
- sum + =(sum >> 16);這一步的目的是什麼?添加剩餘字節?但是,循環中已經添加了剩餘的字節?
謝謝!關於IP校驗碼
可以格式化你的代碼一點,好嗎? – WhirlWind 2010-04-05 19:19:24
有人需要清理它。 :( – Rev316 2010-04-05 19:19:37
'ip_hdr'不能是27個字節,它們必須是4個字節長的倍數,並且長度必須在20到60個字節之間 - '(4 * ip_hdr-> ip_ihl)',因爲'ip_ihl'是一個四位的字段 – Alnitak 2014-11-06 08:46:22