如何将ipv6地址解析为“八位字节"? [英] How to parse ipv6 address into "octets"?

查看:181
本文介绍了如何将ipv6地址解析为“八位字节"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将ipv6地址解析为八位字节.有什么类似的东西吗?

I want to be able to parse ipv6 address into octets. Is there something similar to the following?

IPAddress.Parse(address).GetAddressBytes()[0];
IPAddress.Parse(address).GetAddressBytes()[1];

推荐答案

您的意思是这样吗?

IPAddress ipv6Addr = IPAddress.Parse("FE80::0202:B3FF:FE1E:8329") ;
byte[]    octets   = ipv6Addr.GetAddressBytes() ;

string text = String.Join( "," , octets.Select( x => string.Format("0x{0:X2}", x ) ) ) ;
Console.WriteLine(text);

上面的代码片段将其写入控制台:

The above snippet writes this to the console:

0xFE,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x02,0xB3,0xFF,0xFE,0x1E,0x83,0x29

如您所愿.

编辑后注意:您可能想了解如何将IPv6地址表示为 text :

Edited to Note: You might want to read up on how IPv6 addresses are represented as text:

  • http://tools.ietf.org/html/rfc5952
  • http://tools.ietf.org/search/rfc1924

IPv4地址的长度为32位整数(4个八位位组),并以点分四进制"表示法以文本表示:x.x.x.x,其中每个"x"是所讨论的八位位组的十进制值.

IPv4 addresses are a 32 bit integer (4 octets) in length and are represent in text using "dotted quad " notation: x.x.x.x, where each 'x' is the decimal value of the octet in question.

IPv6地址为128位(长度为16个八位位组).规范的文本表示形式是用十六进制形式表示的8个16位整数,用冒号分隔:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx,尽管有许多种方法可以操纵它,以使表示形式更紧凑.

IPv6 addresses are 128 bits (16 octets in length). The canonical textual representation is as 8 16-bit integers shown in hexadecimal form, separated by colons: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx, though there are a number of ways to manipulate that so as to make the representation more compact.

要从注释中获得所需的内容,您需要获取16个八位字节的数组,并将每对八位字节转换为ushort.

To get what you appear to want from your comment, you'll need to take the array of 16 octets you get and convert each pair of octets into a ushort.

不过,您应该注意,文本表示是以网络字节顺序(big-endian,唯一合适的体系结构,恕我直言)的IP地址.英特尔芯片是低端的.您需要考虑到这一点.有关字节序和网络字节顺序的更多信息,请参见: http://en.wikipedia.org/wiki/Endianness

You should note though, that the textual represention is of the IP address in network byte order (big-endian, the only proper architecture, IMHO). Intel chips are little-endian. You'll need to take that into account. More on endianness and network byte order here: http://en.wikipedia.org/wiki/Endianness

这篇关于如何将ipv6地址解析为“八位字节"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆