简体   繁体   English

在C中计算IP校验和

[英]Calculating IP checksum in C

I looked at RFC 1071 for some information on calculating the IP checksum. 我查看了RFC 1071 ,了解有关计算IP校验和的一些信息。 For the application I'm making, I need to calculate the IP checksum of a 20 byte IP header (no options). 对于我正在制作的应用程序,我需要计算20字节IP标头的IP校验和(无选项)。 My code is as follows: 我的代码如下:

uint16_t calculate_ip_chksum(IP *ip)
{
    uint16_t *buf = (uint16_t *) ip;
    uint32_t sum = 0;
    uint16_t checksum = 0;

    int counter = (ip->version & 0xF) * 4;
    while (counter > 1)
     {
            sum += *buf++;
            counter -= 2;
     }

    if (counter == 1)
            sum += * (uint8_t *) buf;

    while (sum >> 16)
            sum = (sum & 0xFFFF) + (sum >> 16);
    checksum = ~sum;
    return checksum;
}

I defined an IP header as follows: 我定义了一个IP标头,如下所示:

typedef struct ip_h
{
    uint8_t version;
    uint8_t tos;
    uint16_t tot_len;
    uint16_t id;
    uint16_t frag_off;
    uint8_t ttl;
    uint8_t proto;
    uint16_t chksum;
    uint32_t src;
    uint32_t dst;

} IP;

I understand the mathematics of how to calculate the checksum, but I do not understand why my code (which is almost exactly the same as the RFC) does not work. 我了解如何计算校验和的数学方法,但是我不明白为什么我的代码(与RFC几乎完全相同)为什么不起作用。

You derive counter from ip->version instead of tot_len. 您从ip-> version而不是tot_len派生计数器。

 int counter = (ip->version & 0xF) * 4;

I assume that you want total number of bytes in the buffer for checksum. 我假设您想要缓冲区中的总字节数作为校验和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM