UDP checksum and code

UDP checksum adopts inverse code summation: two numbers are added, and the excess 16 bits are added to the 0th bit.

// checksum algorithm

unsigned short UDPCheck(unsigned short *data, int len)
{
    int carryBit=0;
    int sum = 0;
    for (int i = 0; i < len; i++)
    {
        sum += data[i];
        sum = (sum & 0xFFFF) + ((sum >> 16) & 0x1);
    }
    return ~(sum & 0xFFFF);
}


void main()
{

    unsigned short udpData[] = {0x9913,0x0868,0xab03,0x0e0b,0x0011,0x000f,0x043f,0x000d,0x000f,0x0000,0x5445,0x5354,0x494e,0x4700};

    unsigned short check = UDPCheck(udpData,14);
    printf("%4x\n",check);
    getchar();

}

Guess you like

Origin blog.csdn.net/wyyy2088511/article/details/130032817