Internet checksum 算法(Ip checksum)

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

猜你喜欢

转载自blog.csdn.net/vegeta852/article/details/109853185