From 32b0562375425e0c233f4d8ea7085fb4c83a57b2 Mon Sep 17 00:00:00 2001 From: Gregory Nutt Date: Sun, 4 Oct 2020 11:22:32 -0600 Subject: [PATCH] Add some comments to inet_ntop() Endian-ness issues are mind boggling sometimes. I have been confused by the logic in inet_ntop() a few times so I thought I would add some comments so that I (and others) will understand the endian-ness issues in the future. No change to logic, only comments changed. --- libs/libc/net/lib_inetntop.c | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/libs/libc/net/lib_inetntop.c b/libs/libc/net/lib_inetntop.c index aa566083ffa..17780512628 100644 --- a/libs/libc/net/lib_inetntop.c +++ b/libs/libc/net/lib_inetntop.c @@ -98,7 +98,8 @@ ****************************************************************************/ #if defined(CONFIG_NET_IPv4) || defined(CONFIG_LIBC_IPv4_ADDRCONV) -static int inet_ipv4_ntop(FAR const void *src, FAR char *dest, socklen_t size) +static int inet_ipv4_ntop(FAR const void *src, FAR char *dest, + socklen_t size) { FAR uint8_t *ptr; @@ -108,8 +109,33 @@ static int inet_ipv4_ntop(FAR const void *src, FAR char *dest, socklen_t size) } ptr = (FAR uint8_t *)src; + + /* Data is in network order. However, indexed access is the same in both + * big and little endian cases: + * + * Big Endian: + * +---+---+---+---+ + * Network Order: | 0 | 1 | 2 | 3 | n=Network byte order + * |192|168| 1 | 2 | Example + * +---+---+---+---+ + * Host Index: | 0 | 1 | 2 | 3 | n=Host Index + * |192|168| 1 | 2 | Example + * +---+---+---+---+ + * + * Little Endian: + * + * +---+---+---+---+ + * Network Order: | 0 | 1 | 2 | 3 | n=Network byte order + * |192|168| 1 | 2 | Example + * +---+---+---+---+ + * Host Index: | 3 | 2 | 1 | 0 | n=Host Index + * | 2 | 1 |168|192| Example + * +---+---+---+---+ + */ + snprintf(dest, INET_ADDRSTRLEN, "%u.%u.%u.%u", ptr[0], ptr[1], ptr[2], ptr[3]); + return OK; } #endif @@ -143,7 +169,8 @@ static int inet_ipv4_ntop(FAR const void *src, FAR char *dest, socklen_t size) ****************************************************************************/ #if defined(CONFIG_NET_IPv6) || defined(CONFIG_LIBC_IPv6_ADDRCONV) -static int inet_ipv6_ntop(FAR const void *src, FAR char *dest, socklen_t size) +static int inet_ipv6_ntop(FAR const void *src, FAR char *dest, + socklen_t size) { FAR const struct in6_addr *in6_addr; uint16_t warray[8]; @@ -180,6 +207,7 @@ static int inet_ipv6_ntop(FAR const void *src, FAR char *dest, socklen_t size) { break; } + offset++; count++; } @@ -190,6 +218,7 @@ static int inet_ipv6_ntop(FAR const void *src, FAR char *dest, socklen_t size) maxcount = count; } } + offset++; } @@ -260,7 +289,7 @@ FAR const char *inet_ntop(int af, FAR const void *src, FAR char *dest, { int ret; - DEBUGASSERT(src && dest); + DEBUGASSERT(src != NULL && dest != NULL); /* Do the conversion according to the IP version */