- 论坛徽章:
- 0
|
本人目前在用Java做OSPF嗅探程序,发现抓下来的包,校验和总是不对。(OSPF里用的校验算法是“Fletcher Checksum”), 按照算法自己写了个两个小程序,一个用c,一个用Java (见下面),都是用数组做测试, 结果仍然不对。
察看zebra/ospfd 里面的这段代码,发现里面的指针变量,指的地址早已经超出了原来的包的地址范围,也就是说 p 指针里面的东西,已经不是原来包的内容了!!
但是下面的ospf代码应该没有问题,这种情况下,想问问用Java该如何实现这种指针操作呢?或者更广泛地说,Java下,如果做这种校验呢?希望有经验的赐教一下。不胜感谢!
/* Fletcher Checksum -- Refer to RFC1008. */
#define MODX 4102
#define LSA_CHECKSUM_OFFSET 15
u_int16_t
ospf_lsa_checksum (struct lsa_header *lsa)
{
u_char *sp, *ep, *p, *q;
int c0 = 0, c1 = 0;
int x, y;
u_int16_t length;
lsa->checksum = 0;
//Q1: ntohs 把网络16比特转化为主机值
// 这样,如果包的长度原来为30, 转换后,就变成了7680
length = ntohs (lsa->length) - 2;
sp = (char *) &lsa->options;
for (ep = sp + length; sp < ep; sp = q)
{
q = sp + MODX;
if (q > ep)
q = ep;
for (p = sp; p < q; p++)
{
c0 += *p;
// p 指针的内容,一旦超出了包的长 度,里面的内容,不就是随机的了么,怎么保证校验的正确呢?
c1 += c0;
}
c0 %= 255;
c1 %= 255;
}
x = ((length - LSA_CHECKSUM_OFFSET) * c0 - c1) % 255;
if (x <= 0)
x += 255;
y = 510 - c0 - x;
if (y > 255)
y -= 255;
/* take care endian issue. */
lsa->checksum = htons ((x << + y);
return (lsa->checksum);
}
public static long caculateChecksum_2(int[] content, int start, int len) // can be seen it is from c version. 
{
/* Fletcher Checksum -- Refer to RFC1008. */
int MODX = 4102;
int LSA_CHECKSUM_OFFSET = 15;
int sp, ep, p, q; // positions
long c0 = 0, c1 = 0;
long x, y;
int length;
long checksum = 0;
//length = lsa.length() - 2;
length = len -start ;
//sp = LSAPacketFields.OPTIONS_POS;
sp = start;
for (ep = sp + length; sp < ep; sp = q)
{
q = sp + MODX;
if (q > ep)
q = ep;
for (p = sp; p < q; p++)
{
c0 += (content[p] & 0xff);
c1 += c0;
}
c0 %= 255;
c1 %= 255;
}
x = ((length - LSA_CHECKSUM_OFFSET) * c0 - c1) % 255;
if (x <= 0)
x += 255;
y = 510 - c0 - x;
if (y > 255)
y -= 255;
/* take care endian issue. */
//checksum = htons ((x << + y);
//checksum = (x << 8 ) + y;
checksum = (x<< 8 ) + y;
return checksum;
} |
|