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