欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Internet checksum 算法(Ip checksum)

程序员文章站 2022-07-10 14:34:09
...

Internet checksum 算法(Ip checksum)

/*****************************************************************************
 * NAME: HeaderChecksum
 *
 * DESCRIPTION:
 *      this function calculates the header's checksum. it is
 *      exactly the Internet checksum (IP checksum) as defined by RFC 1071.
 *
 * INPUTS:
 *      Header          - [in] the pointer to the header octet string.
 *      HeaderLen       - [in] the number of bytes in the header.
 *
 * RETURN:
 *      the checksum in network order.
 */

static
inline
uint16_t
HeaderChecksum(
    char const* Header,
    uint32_t HeaderLen
    )
{
    uint16_t const* endp = (uint16_t const*)(Header + HeaderLen);
    uint16_t const* p16 = (uint16_t const*)Header;
    uint32_t sum = 0;
    
    while (p16 < endp)
    {
        sum += *(p16++);
    }

    sum = (sum >> 16) + (uint16_t)sum;
    sum = (sum >> 16) + (uint16_t)sum;
    return ~(uint16_t)sum;
}