The UDP checksum is calculated to verify the integrity of the UDP header and data. It is optional in IPv4 but mandatory in IPv6. Here is a step-by-step process for calculating the UDP checksum:
- Pseudo-header Preparation: Construct a pseudo-header, which is not actually transmitted but used in the checksum calculation. It includes the following fields:
- Source IP address (4 bytes for IPv4, 16 bytes for IPv6)
- Destination IP address (4 bytes for IPv4, 16 bytes for IPv6)
- Zero (1 byte for IPv4, 3 bytes for IPv6)
- Protocol (1 byte, which is 17 for UDP)
- UDP length (2 bytes, the length of the UDP header and data)
- UDP Header and Data: The actual UDP header and the data are then appended to the pseudo-header for checksum calculation.
- Checksum Calculation:
- Combine the pseudo-header, UDP header, and UDP data.
- If the length of this combination is odd, pad it with a zero byte at the end to make it even.
- Calculate the sum of all 16-bit words in this combination, adding any overflow bits back into the lower 16 bits.
- Take the one’s complement (bitwise NOT) of the result.
- Placement: Place the resulting checksum in the UDP header checksum field.
Here’s a more detailed breakdown:
Pseudo-header Construction (IPv4)
Pseudo-header Construction (IPv6)
UDP Header
Example Calculation (IPv4)
Suppose we have the following:
- Source IP: 192.168.1.1
- Destination IP: 192.168.1.2
- Source Port: 12345
- Destination Port: 24672
- Data: “Hello”
- Pseudo-header:
- UDP Header and Data:
- Combining and Padding:
- Calculating the Sum:
- Sum: Add all 16-bit words together:
- One’s Complement:
- Final UDP Header:
This gives the UDP checksum of 81FF
for the given data.