Improve checksum usages

This commit is contained in:
世界 2025-08-27 11:03:17 +08:00
parent f9bbb15bfb
commit adc106bcf6
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
9 changed files with 23 additions and 45 deletions

View file

@ -479,7 +479,9 @@ func (b IPv4) SetDestinationAddress(addr tcpip.Address) {
// CalculateChecksum calculates the checksum of the IPv4 header.
func (b IPv4) CalculateChecksum() uint16 {
return checksum.Checksum(b[:b.HeaderLength()], 0)
xsum0 := checksum.Checksum(b[:xsum], 0)
xsum0 = checksum.Checksum(b[xsum+2:b.HeaderLength()], xsum0)
return xsum0
}
// Encode encodes all the fields of the IPv4 header.

View file

@ -351,7 +351,9 @@ func (b TCP) SetUrgentPointer(urgentPointer uint16) {
// and the checksum of the segment data.
func (b TCP) CalculateChecksum(partialChecksum uint16) uint16 {
// Calculate the rest of the checksum.
return checksum.Checksum(b[:b.DataOffset()], partialChecksum)
xsum := checksum.Checksum(b[:TCPChecksumOffset], partialChecksum)
xsum = checksum.Checksum(b[TCPChecksumOffset+2:b.DataOffset()], xsum)
return xsum
}
// IsChecksumValid returns true iff the TCP header's checksum is valid.

View file

@ -113,8 +113,10 @@ func (b UDP) SetLength(length uint16) {
// CalculateChecksum calculates the checksum of the UDP packet, given the
// checksum of the network-layer pseudo-header and the checksum of the payload.
func (b UDP) CalculateChecksum(partialChecksum uint16) uint16 {
// Calculate the rest of the checksum.
return checksum.Checksum(b[:UDPMinimumSize], partialChecksum)
// Calculate the rest of the checksum.\
xsum := checksum.Checksum(b[:udpChecksum], partialChecksum)
xsum = checksum.Checksum(b[udpChecksum+2:], xsum)
return xsum
}
// IsChecksumValid returns true iff the UDP header's checksum is valid.