fletcher校验和给出不同的值

时间:2016-10-02 22:15:09

标签: c checksum

我试图在这里使用16位Fletcher校验和。基本上,我的程序通过"发送"来模拟物理层上的流量。并且"接收"两个虚拟实体之间的数据包我打印出两边的数据包,但它们匹配,但我在接收端计算出不同的校验和。

数据包结构:

#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;
}

我对校验和了解不多,并且我将该算法复制到我找到的页面之外,所以如果有人能够理解为什么两个相同数据包的校验和不同,我将非常感激。谢谢!

1 个答案:

答案 0 :(得分:1)

出现此问题是因为您没有将temp数据的地址传递给校验和函数,而是将变量temp存储在堆栈中的地址。

你应该改变

uint16_t checksum = fletcher16((uint8_t const *) &temp, size);

uint16_t checksum = fletcher16((uint8_t const *) temp, size);
                                                ^ no & operator