0
我想在这里使用16位弗莱彻校验和。基本上,我的程序通过在两个虚拟实体之间“发送”和“接收”数据包来模拟物理层上的流量。我正在打印两端的数据包,它们确实匹配,但我在接收端得到了不同的校验和。弗莱彻校验和给出不同的值
报文结构:
#define MESSAGE_LENGTH 20
struct pkt {
int seqnum;
int acknum;
int checksum;
char payload[MESSAGE_LENGTH];
};
这是我使用来计算每个数据包的校验码:
/*
* Computes the fletcher checksum of the input packet
*/
uint16_t calcChecksum(struct pkt *packet) {
/* the data for the checksum needs to be continuous, so here I am making
a temporary block of memory to hold everything except the packet checksum */
size_t sizeint = sizeof(int);
size_t size = sizeof(struct pkt) - sizeint;
uint8_t *temp = malloc(size);
memcpy(temp, packet, sizeint * 2); // copy the seqnum and acknum
memcpy(temp + (2*sizeint), &packet->payload, MESSAGE_LENGTH); // copy data
// calculate checksum
uint16_t checksum = fletcher16((uint8_t const *) &temp, size);
free(temp);
return checksum;
}
/*
* This is a checksum algorithm that I shamelessly copied off a wikipedia page.
*/
uint16_t fletcher16(uint8_t const *data, size_t bytes) {
uint16_t sum1 = 0xff, sum2 = 0xff;
size_t tlen;
while (bytes) {
tlen = bytes >= 20 ? 20 : bytes;
bytes -= tlen;
do {
sum2 += sum1 += *data++;
} while (--tlen);
sum1 = (sum1 & 0xff) + (sum1 >> 8);
sum2 = (sum2 & 0xff) + (sum2 >> 8);
}
/* Second reduction step to reduce sums to 8 bits */
sum1 = (sum1 & 0xff) + (sum1 >> 8);
sum2 = (sum2 & 0xff) + (sum2 >> 8);
return sum2 << 8 | sum1;
}
我不知道很多关于校验和我复制的算法关闭我找到的页面,所以如果任何人都能理解为什么两个相同的数据包的校验和不同,我将不胜感激。谢谢!
谢谢!我现在感到很傻。最初温度不是一个指针,但当我改变了,我忘记了改变fletcher呼叫。 – xjsc16x