【发布时间】:2011-02-04 13:13:58
【问题描述】:
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 在 16bits 字的数量,而不是 8bits 字节(如果有奇数字节,nword 舍入到下一个大),是否正确?假设 ip_hdr 总共有 27 个字节,那么 nword 将是 14 而不是 13,对吗?
- 这一行 sum = (sum >> 16) + (sum & 0xffff) 是加进位做 16bit 补码
- sum += (sum >> 16);这一步的目的是什么?添加剩余字节?但是循环中已经添加了剩余字节?
谢谢!
【问题讨论】:
-
你能把你的代码格式化一下吗?
-
有人需要清理它。 :(
-
ip_hdr不能是 27 个字节,它们的长度必须是 4 个字节的倍数,并且长度必须在 20 到 60 个字节之间 -(4 * ip_hdr->ip_ihl)因为ip_ihl是一个四字节-位字段。
标签: header checksum ip-protocol