[PATCHv2] libbb/inet_cksum: fix for big endian systems

Baruch Siach baruch at tkos.co.il
Thu Sep 8 08:09:36 UTC 2011


This assignment via pointer dance is required, because we need the last byte to
be considered as MSB of a 16bit word, as if we had one more '\0' byte in
buffer.  Note that the generated checksum is the same on big and little endian
machines in terms of memory representation.  They differ, however, in their
numeric representation.  So, for example the checksum of

    uint8_t buf[] = {0x12, 0x34, 0x56};

is 0xcb97 on little endian machines, and 0x97cb on big endian machines. This
is OK since we use the memory representation of the network packet.

Signed-off-by: Baruch Siach <baruch at tkos.co.il>
---

Changes from v1:
	Fix compile breakage

 libbb/inet_cksum.c |    9 +++++++--
 1 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/libbb/inet_cksum.c b/libbb/inet_cksum.c
index 31bf8c4..99224a2 100644
--- a/libbb/inet_cksum.c
+++ b/libbb/inet_cksum.c
@@ -21,8 +21,13 @@ uint16_t FAST_FUNC inet_cksum(uint16_t *addr, int nleft)
 	}
 
 	/* Mop up an odd byte, if necessary */
-	if (nleft)
-		sum += *(uint8_t*)addr;
+	if (nleft) {
+		/* Make sure that the left-over byte is added correctly both
+		 * with little and big endian hosts */
+		uint16_t tmp = 0;
+		*(uint8_t*)&tmp = *(uint8_t*)addr;
+		sum += tmp;
+	}
 
 	/* Add back carry outs from top 16 bits to low 16 bits */
 	sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
-- 
1.7.5.4



More information about the busybox mailing list