November 22, 2022

BSD TCP/IP for Kyu - checksums

We have two to worry about. The IP checksum and the TCP checksu.

The IP checksum is typically computed at the last minute before the packet gets sent. It covers the first 20 bytes (just the IP header).

The TCP checksum has some special tricks. Just to surprise the innocent programmer, it includes some fields of the IP header, but not all of them. The way the game is played is to zero the IP header and fill in the fields that TCP worries about. Then after TCP has calculated its checksum, the other fields in the IP header can get filled in and then the IP checksum can get calculated.

The IP header is 20 bytes in size, but the TCP checksum only worries about 12 of those bytes, namely:

4 byte source IP
4 byte destination IP
2 byte protocol (6 for TCP)
2 byte payload length
Note that if any monkey business is done with the IP addresses, the TCP checksum will need to be recalculated. It doesn't worry about:
The initial 0x45 for version and header length
The 1 byte TOS
The 2 byte ID counter
The 2 byte offset
The 1 byte TTL
If you are worrying that these don't add up to 20 bytes, consider that the 2 byte checksum itself isn't being counted. Also the 1 byte TTL is the top byte in what I call the "2 byte protcol" (but is set to zero for the TCP calculation.

The code in tcp_input that validates checksums handles these extra fields in the IP header via a number of tricks that make for efficient but very confusing code.


Have any comments? Questions? Drop me a line!

Kyu / [email protected]