[Winpcap-users] TCP Checksum Calculation

he tao hetaozju at gmail.com
Sat Jul 14 08:04:32 GMT 2007


Try this

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 TcpCheckSum(IP* iph,TCP* tcph,char* data,int size)
{
	tcph->Chksum=0;
	PSD_HEADER psd_header;
	psd_header.m_daddr=iph->DstAddr;
	psd_header.m_saddr=iph->SrcAddr;
	psd_header.m_mbz=0;
	psd_header.m_ptcl=IPPROTO_TCP;
	psd_header.m_tcpl=htons(sizeof(TCP)+size);

	char tcpBuf[65536];
	memcpy(tcpBuf,&psd_header,sizeof(PSD_HEADER));
	memcpy(tcpBuf+sizeof(PSD_HEADER),tcph,sizeof(TCP));
	memcpy(tcpBuf+sizeof(PSD_HEADER)+sizeof(TCP),data,size);
	return tcph->Chksum=CheckSum((USHORT *)tcpBuf,
		sizeof(PSD_HEADER)+sizeof(TCP)+size);
}

On 7/13/07, ceo at triplebit.com <ceo at triplebit.com> wrote:
>
>
> Is there any good C/C++ reference for calculating TCP/IP Checksum?
>
> Regards
>
> I. Lesher
> _______________________________________________
> Winpcap-users mailing list
> Winpcap-users at winpcap.org
> https://www.winpcap.org/mailman/listinfo/winpcap-users
>
>


More information about the Winpcap-users mailing list