关于ip校验码的问题
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,对吧?
- sum = (sum >> 16) + (sum & 0xffff) 行是添加进位,得到 16 位补码
- sum += (sum >> 16);这一步的目的是什么?添加剩余字节?但是剩余的字节已经添加到循环中了?
谢谢!
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);
}
- I assume nwords in the number of 16bits word, not 8bits byte (if there are odd byte, nword is rounded to next large), is it correct? Say ip_hdr has 27 bytes totally, then nword will be 14 instead of 13, right?
- The line sum = (sum >> 16) + (sum & 0xffff) is to add carry over to make 16bit complement
- sum += (sum >> 16); What's the purpose of this step? Add left-over byte? But left-over byte has already been added in the loop?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是对的。步骤 3 将 32 位长的 sum 压缩为 16 位无符号短,即校验和的长度。这是出于性能目的,允许计算校验和而不跟踪溢出直到最后。它在步骤 2 和步骤 3 中都执行此操作,因为它可能已从步骤 2 溢出。然后它仅返回求和的反转后的低 16 位。
这有点清楚了:
http://www.sysnet.ucsd.edu/~cfleizac/iptcphdr.html< /a>
You're correct. Step 3 condenses sum, a 32-bit long, into a 16-bit unsigned short, which is the length of the checksum. This is for performance purposes, allowing one to calculate the checksum without tracking overflow until the end. It does this both in step 2 and step 3 because it may have overflowed from step 2. Then it returns just the inverted lower 16 bits of sum.
This is a bit clearer:
http://www.sysnet.ucsd.edu/~cfleizac/iptcphdr.html