How can I compute the checksum of an ICMP echo request or reply when the checksum should include the data portion, the data portion can be variable sized, and there's no way to anticipate the data size?
Here's documentation on how to compute the checksum of an ICMP header.
ICMP Header Checksum. 16 bits. The 16-bit one's complement of the one's complement sum of the ICMP message, starting with the ICMP Type field. When the checksum is computed, the checksum field should first be cleared to 0. When the data packet is transmitted, the checksum is computed and inserted into this field. When the data packet is received, the checksum is again computed and verified against the checksum field. If the two checksums do not match then an error has occurred.
When the sender is calculating the checksum, the value is inserted into the zero'd field. The receiver then does the reverse, it pulls out the checksum, zeros the field and computes the checksum with this field set to zeros. It compares the value it calculated to the one it extracted.
Both sides of the transmission calculate the checksum with the field zero'd out.
Update
An example of how to perform this calculation exists on this Scribd presentation, starting on slide 44. I'm also including the relevant example slide below.
Figure 9.19 shows an example of checksum calculation for a simple echo-request message (see Figure 9.14). We randomly chose the identifier to be 1 and the sequence number to be 9. The message is divided into 16-bit (2-byte) words. The words are added together and the sum is complemented. Now the sender can put this value in the checksum field.
You split the ICMP header and data into 16 bit words (using 0x0000 for the checksum field), get the sum of these words and then the ones complement of the sum. This is then inserted into the checksum field.