我一直在尝试计算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);
}
希望得到一些帮助。
答案 0 :(得分: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);
}