【问题标题】:Calculate LSA checksum in OSPF在 OSPF 中计算 LSA 校验和
【发布时间】:2015-05-25 12:36:48
【问题描述】:

我一直在尝试计算 OSPF 数据包的 LSA 校验和,但没有成功。

我阅读了 ospf 的 RFC 并说您需要使用 Fletcher 算法。我试过了,但它仍然没有给出正确的答案。我的代码:

Void calccksum(lsaHeader* lsa)
{
  lsa->checksum = 0;
  unsigned short answer = 0;
  unsigned char* ptr = (unsigned char*) lsa;
  int len = ntohs(lsa->len);

  // skip the age field
  ptr += 2;
  len -= 2;

  unsigned short sum1 = 0;
  unsigned short sum2 = 0;

  for (int i=0; i<len; i++)
  {
     sum1 += *ptr;
     if (sum1 >= 255)
        sum1 -= 255;
     sum2 += sum1;
     if (sum2 >= 255)
        sum2 -= 255;
     ptr++;
    }
   answer = (sum2 << 8) | sum1;
   lsa->checksum = ntohs(answer);
}

希望得到一些帮助。

【问题讨论】:

  • 这可能是一个愚蠢的问题:answer = (sum2 &lt;&lt; 8) | sum 1; 中的 sum 1 部分是否也包含在您的实际代码中?这样可以编译吗?
  • 我编辑过:只是打错了

标签: c++ checksum ospf


【解决方案1】:
void calccksum(lsaHeader* lsa)
{
   unsigned char* data  = (unsigned char*) lsa;
   unsigned short bytes = ntohs(lsa->len);
   unsigned short sum1  = 0xff, sum2 = 0xff;

   /* RFC : The Fletcher checksum of the complete contents of the LSA,
    *       including the LSA header but excluding the LS age field.
    */
   data += 2; bytes -= 2;

   lsa->checksum = 0;
   while (bytes) {
       size_t len = bytes > 20 ? 20 : bytes;
       bytes -= len;
       do {
           sum2 += sum1 += *data++;
       } while (--len);
       sum1 = (sum1 & 0xff) + (sum1 >> 8);
       sum2 = (sum2 & 0xff) + (sum2 >> 8);
   }
   sum1 = (sum1 & 0xff) + (sum1 >> 8);
   sum2 = (sum2 & 0xff) + (sum2 >> 8);
   lsa->checksum = htons(sum2 << 8 | sum1);
}

【讨论】:

  • 鼓励添加一些关于这段代码如何提供帮助的描述。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2010-12-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多