1

我一直在尝试计算 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);
}

很想得到一些帮助。

4

1 回答 1

0
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);
}
于 2015-10-17T07:32:24.877 回答