# Internet checksum

Internet checksum uses the summing method for calculation and verification of checksum.
https://www.rfc-editor.org/rfc/rfc1071 explains the internet checksum. This method is used in detecting errors in IP, TCP pacckets. This method can detect errors such as single bit or some multi bit errors but not all errors.

The Internet checksum algorithm is outlined as follows:
- Pair adjacent octets to create 16-bit integers, then form the 1’s complement sum of these integers.
- To generate a checksum, clear the checksum field, compute the 16-bit 1’s complement sum over the octets, and place the 1’s complement of this sum in the checksum field.
- To verify a checksum, compute the 1’s complement sum over the same octets, including the checksum field. If the result is all 1 bits (-0 in 1’s complement arithmetic), the check is successful.

The given sequence of octets A, B, C, D, …, Y, Z can be summed to compute a 16-bit checksum using the one’s complement addition using the notation [a,b] for the 16-bit integer a*256+b, where a and b are bytes. Two cases are considered:
For an even count of bytes, the sum includes all the pairs of bytes from A, B to Y, Z, denoted as [A,B] +’ [C,D] +’ … +’ [Y,Z].
For an odd count of bytes, the sum includes pairs of bytes from A, B to Y, Z, and an additional zero byte, denoted as [A,B] +’ [C,D] +’ … +’ [Z,0].
In both cases, +’ represents one’s complement addition.
On a 2’s complement machine, the 1’s complement sum must be computed by means of an “end around carry”, i.e., any overflows from the most significant bits are added into the least significant bits.

To speed this checksum calculations, following methods can be used:
- Parallel summation: On 32 bit /64 bit machines, add 4/8 bytes at a time. When the sum has been computed, we “fold” the long sum into 16 bits by adding the 16-bit segments. Each 16-bit addition may produce new end-around carries that must be added.
-Deferred carries: Defer adding the end around carries until the main summation loop is finished.
-Incremental update: Updating a checksum can be done without rescanning the entire message by just adding the differences of the sixteen-bit integers.
Given the original value m, the new value m’, and the old checksum C, the new checksum C’ is:
C’ = C + (-m) + m’ = C + (m’ — m)