# Calculating the TCP checksum value - TCP Length & Padding

0

I'm attempting to calculate the TCP checksum value (which apparently is the same as the IP4 checksum) but getting the wrong results. I think the issue is arrising from either the padding at the end or the TCP header field but I can't find any details (from the RFC) on how they should be calculated.

For building the pseudoheader (wiki) I'm using the following code to bring together the data (field('xyz').bin() returns a binary string of the field xyz.):

public String genChecksum()
{

// From IPv4 - Pseudo Header
pseudoHeader += "00000000"; // reserved block

/* TCP Length field:
* dataSize() = (IP4.totalLength * 8) - ((IP4.internetHeaderLength * 32) + (TCP.dataOffset * 32))
*/

pseudoHeader += "0000000000000000"; // checksum zeroed out

// Pad to 16 bit boundary as stated in RFC
for (int i = 0; i < (pseudoHeader.length() % 16); i++)
{
}

}

I'm fairly sure the values in pulling together (field() and peekField() are correct, I've verified them with wireshark & the checksum of IP4 is correct. The actual checksum method is included below but i've got a test to check that's correct too:

public static String CRC16(String hex)
{
byte[] buf = Types.hexToBytes(hex);
int length = buf.length;
int i = 0;

long sum = 0;
long data;

while (length > 1)
{
data = (((buf[i] << 8) & 0xFF00) | ((buf[i + 1]) & 0xFF));
sum += data;

if ((sum & 0xFFFF0000) > 0)
{
sum = sum & 0xFFFF;
sum += 1;
}

i += 2;
length -= 2;
}

if (length > 0)
{
sum += (buf[i] << 8 & 0xFF00);

if ((sum & 0xFFFF0000) > 0)
{
sum = sum & 0xFFFF;
sum += 1;
}
}

sum = ~sum;
sum = sum & 0xFFFF;

System.out.println("CRCV: " + String.format("%X", sum));
return String.format("%X", sum);
}

public static void assertTestChecksum()
{
byte[] buf = {(byte) 0xe3, 0x4f, 0x23, (byte) 0x96, 0x44, 0x27, (byte) 0x99, (byte) 0xf3};

if (!CRC16(Types.bytesToHex(buf)).equals("1AFF"))
{
Utils.exit("Checksum.java", "assertTestChecksum() failed.");
}
}

Am I doing anything overtly wrong?

java
tcp
checksum
libpcap
asked on Stack Overflow May 29, 2019 by Crizly • edited May 29, 2019 by Crizly