IP Header Checksum计算c实现

原文连接 http://blog.csdn.net/yhangleo/article/details/8508003


一直有疑问,计算checksum的时候 ,自身算不算进去计算,下面的文章告诉你


关于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。


代码:

[cpp]  view plain  copy
  1. _Int16 GetIpCheckSum( Byte *ptr, int size)  
  2. {  
  3.     int cksum = 0;  
  4.     int index = 0;  
  5.       
  6.     *(ptr + 10) = 0;  
  7.     *(ptr + 11) = 0;  
  8.   
  9.     if(size % 2 != 0)  
  10.         return 0;  
  11.       
  12.     while(index < size)  
  13.     {          
  14.         cksum += *(ptr + index + 1);  
  15.         cksum += *(ptr + index) << 8;  
  16.   
  17.         index += 2;  
  18.     }  
  19.   
  20.     while(cksum > 0xffff)  
  21.     {  
  22.         cksum = (cksum >> 16) + (cksum & 0xffff);  
  23.     }  
  24.     return ~cksum;  
  25. }  

ps:发送前需要将结果转换为网络序
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值