// ip_checksum.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
typedef unsigned short USHORT ;
typedef unsigned char UCHAR ;
/*
*函数名称:check_sum
* 传入参数:unsigned char *ptr,指向需要计算checksum的unsigned char数组;
* int size,数组的长度,传入的数组的长度必须为偶数
* 返回:返回一个unsigned short的值
*/
unsigned short check_sum(unsigned char *ptr, int size)
{
if(size % 2 != 0)
{
return 0;
}
int cksum = 0;
int index = 0;
while(index < size)
{
cksum += *(ptr + index + 1);
cksum += *(ptr + index) << 8;
index += 2;
}
while(cksum > 0xffff)
{
cksum = (cksum >> 16) + (cksum & 0xffff);
}
return ~cksum;
}
//
USHORT checksum(USHORT *buffer, int size)
{
unsigned long cksum=0;
while (size > 1)
{
cksum += *buffer++;
size -= sizeof(USHORT);
}
if (size)
{
cksum += *(UCHAR*)buffer;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
USHORT checksum2(USHORT *buffer, int size)
{
unsigned long cksum=0;
while (size > 1)
{
cksum += *buffer++;
size -= sizeof(USHORT);
}
if (size)
{
cksum += *(UCHAR*)buffer;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
int main()
{
// unsigned char ptr[] = {0x45, 0x00, 0x00, 0x1c, 0x00, 0x0b, 0x00, 0x00, 0x80, 0x01,
// 0xc0, 0xa8, 0x01, 0x17, 0xc0, 0xa8, 0x01, 0x1b};
unsigned char ptr[] = {0x45, 0x00, 0x00, 0x28, 0x6c, 0x4e, 0x40, 0x00, 0x80, 0x06,
0xc0, 0xa8, 0x5a, 0x64, 0x71, 0xf6, 0x86, 0xe5};
printf("%x\n", checksum2((USHORT*)ptr, 18));
USHORT us = check_sum(ptr, 18);
printf("%x\n",us );
system("pause");
return 0;
}