如何初始化struct in6_addr?

问题描述 投票:3回答:2

我知道有一种方法可以做到这一点,

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

但不能用这个,

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

似乎我可以1/2/3巴黎的括号。为什么?

谢谢。

network-programming ipv6
2个回答
2
投票

因为需要指出它正在寻址的地址形式(使用C99显示):

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

第一个括号对用于in6_addr结构,第二个用于结合:

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

8
投票

这样做的便携方式是这样的:

struct in6_addr s6 = { };
if (!IN6_IS_ADDR_UNSPECIFIED(&s6))
  inet_pton(AF_INET6, "2001:db8::1", &s6);
© www.soinside.com 2019 - 2024. All rights reserved.