Search code examples
clinuxipv6endianness

How to convert ipv6 address from network order to host order


Say, ipv6 is defined as:

struct in6_addr
{
    union 
    {
        __u8        u6_addr8[16];
        __be16      u6_addr16[8];
        __be32      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
};

For ipv4 (32 bit integer), we convert endianess as (using htonl()):

Little endian: 0x0A0B0C0D
Big endian   : 0x0D0C0B0A

I am parsing a packet from network. So, if I consider ipv6 as u6_addr32[4], is following correct?

u32_nw_order[0] = inet_ntop(u32_host_order[3])
u32_nw_order[1] = inet_ntop(u32_host_order[2])
u32_nw_order[2] = inet_ntop(u32_host_order[1])
u32_nw_order[3] = inet_ntop(u32_host_order[0])

What's the correct way to deal with endianness conversion for 128 bit IPv6 address?


Solution

  • You don't need to, IPv6 addresses arn't encoded or handled as multi-byte integers, so there's no concept of network/host endian regarding those. An IPv6 address is just a sequence of 16 bytes.

    So, if I consider ipv6 as u6_addr32[4]

    Don't do that, there would normally be no reason to - just deal the __u8 u6_addr8[16];