关于tcp/udp协议中校验和填充0的问题

执剑者罗辑 2017-11-03 01:07:23
在UDP报文校验和计算的时候,如果报文的数据部分不是偶数个字节,则在最后面填充0。
在RFC1071的文档中,有一个C语言的的代码来求解校验和。代码如下
   in 6
{
/* Compute Internet Checksum for "count" bytes
* beginning at location "addr".
*/
register long sum = 0;

while( count > 1 ) {
/* This is the inner loop */
sum += * (unsigned short) addr++;
count -= 2;
}

/* Add left-over byte, if any */
if( count > 0 )
sum += * (unsigned char *) addr;

/* Fold 32-bit sum to 16 bits */
while (sum>>16)
sum = (sum & 0xffff) + (sum >> 16);

checksum = ~sum;
}

其中,有一句代码是
if( count > 0 )
sum += * (unsigned char *) addr;

如果是奇数个字节,代码中在最后好像是直接加上最后一个字节,并没有填充0。而且我在网上看到的很多都是这一种求法,为什么是这种求法呢?而不是这样求呢?
if( count > 0 )
sum += (* (unsigned char *) addr) << 8;
...全文
1046 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
dolphin98629 2017-11-13
  • 打赏
  • 举报
回复
uint16 IP_CheckSum(void *dataptr, uint16 len) { uint32 acc = 0; uint16 *octetptr = (uint16*)dataptr; /* dataptr may be at odd or even addresses */ while(len >= 2) { acc += ntoh16(*octetptr); octetptr++; len -= 2; } if(len > 0) { acc += ((*(uint8*)octetptr) << 8); } /* add deferred carry bits */ acc = (acc >> 16) + (acc & 0x0000ffffUL); if ((acc & 0xffff0000UL) != 0) { acc = (acc >> 16) + (acc & 0x0000ffffUL); } /* This maybe a little confusing: reorder sum using htons() instead of ntohs() since it has a little less call overhead. The caller must invert bits for Internet sum ! */ return ~ hton16((uint16)acc); } 上面是我们代码的实现,考虑大小端的问题话需要使用sum += (* (unsigned char *) addr) << 8; 楼主贴的代码是在不同大小端机器运行结果会不一样的
qq_20996085 2017-11-09
  • 打赏
  • 举报
回复
因为计算的时候直接是按16bit算的,sum += * (unsigned char *) addr; 会把最后1字节当做一个2字节的数,数据在高8位,低8位自动就是0了。 也就是说,把最后8位当成一个16位数的高位去相加,不知道能不能理解,我c语言也不好。在这一步已经后面补0了。

1,736

社区成员

发帖
与我相关
我的任务
社区描述
网络协议与配置相关内容讨论专区
网络协议网络安全tcp/ip 技术论坛(原bbs)
社区管理员
  • 网络协议与配置社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧