Search code examples
network-programmingipv6

How to initialize struct in6_addr?


I do know one method to do this,

const struct in6_addr naddr6 = { { 
                0x3f, 0xfe, 0x05, 0x01,
                0x00, 0x08, 0x00, 0x00, 
                0x02, 0x60, 0x97, 0xff,
                0xfe, 0x40, 0xef, 0xab
}};

but could not with this,

const struct in6_addr naddr6 = 
                { { { 0x3ffe0501, 0x00080000, 0x026097ff, 0xfe40efab } } }; 

and it seems that I could either 1/2/3 paris of brackets.Why?

thanks.


Solution

  • Because one need to indicate which form of the address it is addressing (shown using C99):

    const struct in6_addr naddr6 = 
        { { .u6_addr32 = { 0x3ffe0501, 0x00080000, 0x026097ff, 0xfe40efab } } };
    

    The first bracket pair is for the in6_addr struct, the second for the union:

    struct in6_addr
      {
        union
          {
     uint8_t u6_addr8[16];
     uint16_t u6_addr16[8];
     uint32_t u6_addr32[4];
          } in6_u;
      };