Search code examples
network-programmingtcpchecksumcalculation

TCP calculate checksum


I am trying to calculate the checksum of the following packet: A TCP packet captured with wire shark

But I never managed to get the correct checksum (0x67ea).

I tried to calculate it like follows (of course with using one's complement sum):

source IP + destination IP + TCP protocol + (TCP header length + payload length) + payload

c0a8 + ae80 + c0a8 + ae01 + 0006 + 0026 + 6c69 + 646f + 720a = 420df

With the one's complement: 4 + 20df = 20e3

not(20e3) = df1c

Which is defiantly not the current checksum.

I also notice that every time I send the same payload, the checksum is changing so I guess it can't be those same unchanging variables and it must be more (for example timestamp..).

What are the exact parameters and the formula that checksum uses? and how can I calculate it?

Thanks for your help!


Solution

  • You might've overlooked TCP fixed header and TCP options. These bytes also contribute to the checksum (not just TCP payload). Please note that the TCP checksum field (ddff) is replaced with 0 for correct calculation.

    IPv4 SRC + IPv4 DST + IPv4 Protocol + TCP Segment Length +
    
    TCP Fixed Header (with checksum field set to 0) +
    
    TCP Options +
    
    TCP Payload
    

    gives you

    c0a8 + ae80 + c0a8 + ae01 + 0006 + 0026 +
    
    115c + dcba + 28d5 + 41da + 64e8 + 6a10 + 8018 + 01fe + 0000 + 0000 +
                                                           (csum)
    
    0101 + 080a + 5c86 + c6f8 + bd62 e36f + 
    
    6c69 + 646f + 720a
    

    which equals 9980c. Next, 9 + 980c = 9815, and, finally, this will give you 67ea.