我一直在尝试为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);
}
希望能有所帮助。
最佳答案
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);
}
关于c++ - 在OSPF中计算LSA校验和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30438574/