UDP校验和采用反码求和:两数相加,把超出16位加入到第0位。

//校验和算法

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();

}

04-09 06:43