How to compute checksum for TCP packets?

Given code can help you to compute checksum.

/* pseudo header for checksum calculation */
typedef struct pseudoh {
    guint32 src_addr;
    guint32 dest_addr;
    guint8  zero;
    guint8  protocol;
    guint16 length;
} PSEUDO_HDR, * PPSEUDO_HDR;

/* Compute Checksum for TCP packets */
GUINT16 ComputeChecksum(PGUINT16 pseudo_hdr, PGUINT16 ptcp_hdr, PGUINT16 pdata, GUINT32 dataSize) {

  guint32 checksum = 0;
  guint32 nleft = 0;

  nleft = SIZE_PSEUDO_HDR;
  while(nleft > 1) {
    /*  This is the inner loop */
    checksum = checksum + *(pseudo_hdr++);
    nleft = nleft – sizeof(guint16);
  }

  nleft = SIZE_TCP_HEADER;
  while(nleft > 1) {
    /*  This is the inner loop */
    checksum = checksum + *(ptcp_hdr++);
    nleft = nleft – sizeof(guint16);
  }

  nleft = dataSize;
  while(nleft > 1) {
    /*  This is the inner loop */
    checksum = checksum + *(pdata++);
    nleft = nleft – sizeof(guint16);
  }
  if(nleft)
    checksum = checksum + *((pguint8)pdata);
  /*  Fold 32-bit sum to 16 bits */
  checksum = (0xFFFF&(checksum >> 16)) + (checksum & 0xffff);
  checksum = (checksum & 0xffff) + (0xFFFF&(checksum >> 16));
  return (guint16)(~checksum);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s