TCP Checksum
The good way to know how TCP checksum works, is to dig into TCP/IP protocol source code. In brief, TCP checksum is a 16-bits segments in TCP header. At very beginning, checksum is reset to 0. Then, TCP pseudo header, TCP header and TCP data are broken into 16-bits chucks. All these 16 bit words are added together using 1’s complement arithmetic. The result will be loaded to TCP checksum field. After TCP segment is transmitted to the destination, it will be recalculated including TCP pseudo header, TCP header and TCP data. If checksum is oxffff, then, all the data have been transmitted successfully.
The following is checksum function.
unsigned short checkSum(unsigned short *szBUF,int iSize)
{
/* Set checksum to 0 */
unsigned long ckSum=0;
/* All 16-bits chucks are added except last chuck*/
for(;iSize>1;iSize-=sizeof(unsigned short))
ckSum+=*szBUF++;
/* Added the last chuck */
if(iSize==1)
ckSum+=*(unsigned char *)szBUF;
/* The carry over 16 bits should be calculated as well,
Which is hardly mentioned in the explanation.
Some other source code use while loop to realize:
while (ckSum >> 16)
ckSum = (ckSum&0xffff) + (ckSum >> 16);
The code is more matured for IPv6. */
ckSum=(ckSum>>16)+(ckSum&0xffff);
ckSum+=(ckSum>>16);
/* Return negation of checksum */
return(unsigned short )(~ckSum);
}
Discussion Area - Leave a Comment