IP首部校验和计算

计算方法在RFC1071有详细说明。
计算步骤:
1.首先将IP包头校验和字段置0
2.然后将整个IP包头每16bit 相加(相加结果如果有进位,则需将进位加到最低位,RFC1071有相关介绍)
3.最后将相加的结果取反即可

unsigned short checksum(int nCount,unsigned short * addr)
{
    long sum = 0;

    while(nCount > 1)
    {
        sum    += *addr++;
        nCount -= sizeof(unsigned short);
    }

    if(nCount > 0)
    {
        sum += *(unsigned char*)addr;
    }

    while(sum >> 16)
    {
        sum = (sum & 0xFFFF) + (sum >> 16);
    }

    return (unsigned short)(~sum);
}

int main(int argc,char * argv[])
{
    unsigned char IpHeader[] = "\xa1\x00\x00\x45\x00\x00\x21\x2c\x00\x00\x11\x01\x2f\x0a\x1e\xac\xfa\xff\xff\xef"; //抓包示例,此包的检验和是0xe6e3    

    printf("0x%0x\n",checksum(sizeof(IpHeader)-1,(unsigned short *)IpHeader)); //注意后面的'\0'
}

你可能感兴趣的:(网络)