Is network byte order pointless under IPv6?

xmllmx picture xmllmx · Jan 13, 2013 · Viewed 10.4k times · Source

If we use a 32-bit integer to store an IPv4 address, then the byte order of the integer must be considered.

However, as there is no built-in 128-bit integer type under almost all platforms, an IPv6 address must be stored into a byte array, so, I think the byte order is no longer a problem.

Am I correct? Or is there a corresponding function htonlXXX for IPv6?

Answer

mrbultitude picture mrbultitude · Jan 13, 2013

IPv6 does require network byte order for ipv6 addresses. hton and ntoh are all about converting the address from how you have it stored in your code, to how it needs to be stored in the packet (and vice-versa). So the issue becomes how you have it stored in your code.

Also the definition of an IPv6 address in code can allow more ways to address it than just an array of bytes:

struct in6_addr
{
    union 
    {
        __u8 u6_addr8[16];
        __u16 u6_addr16[8];
        __u32 u6_addr32[4];
    } in6_u;
#define s6_addr in6_u.u6_addr8
#define s6_addr16 in6_u.u6_addr16
#define s6_addr32 in6_u.u6_addr32
};

IPv6 addresses, to the user, are represented as 8 16-bit values. If you have the address stored as 8 16-bit values in your code, then you will need to use htons on each 16 bit value as you place it into the packet using the u6_addr16[] array, and use ntohs as you retrieve each 16-bit value from u6_addr16[].

These links are helpful:

http://msdn.microsoft.com/en-us/library/ee175867.aspx

http://en.wikipedia.org/wiki/IPv6_address (especially the diagram at top right)