[英]Why use union to represent IP in IN6_ADDR
I am learning networking on Windows using C.我正在使用 C 在 Windows 上学习网络。 I came across
IN6_ADDR
structure that represents an IPv6 address as a union of 2 arrays:我遇到了
IN6_ADDR
结构,它将 IPv6 地址表示为 2 个 arrays 的联合:
typedef struct in6_addr {
union {
UCHAR Byte[16];
USHORT Word[8];
} u;
} IN6_ADDR, *PIN6_ADDR, *LPIN6_ADDR;
I can't wrap my head around why would someone desire a union of 2 arrays instead of just 1 array.我无法理解为什么有人想要 2 个 arrays 而不是 1 个数组的联合。 What is the reason for such declaration?
这种声明的原因是什么? Note that both arrays are 128 bits long.
请注意,arrays 都是 128 位长。
IPv6 addresses are generally written in a format that uses 2-byte groups, eg IPv6 地址通常以使用 2 字节组的格式编写,例如
2001:0db8:85a3:0000:0000:8a2e:0370:7334
Each of those groups corresponds to an element of the Word
array.这些组中的每一个都对应于
Word
数组的一个元素。
But sometimes it's also useful to process each byte of the address.但有时处理地址的每个字节也很有用。 In this case, you would use the
Byte
array, rather than having to shift and mask elements of Word
.在这种情况下,您将使用
Byte
数组,而不必移动和屏蔽Word
的元素。
IPv6 addresses are typically represented as a group of 16-bit values, for example: IPv6 地址通常表示为一组 16 位值,例如:
2001:0db8:0000:0000:0000:8a2e:0370:7334 2001:0db8:0000:0000:0000:8a2e:0370:7334
The Word
member allows you to read these 16 bit words individually instead of reading a single byte at a time. Word
成员允许您单独读取这些 16 位字,而不是一次读取一个字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.