How to parse ipv6 address into “octets”?

£可爱£侵袭症+ 提交于 2019-12-11 11:40:06

问题


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];

回答1:


You mean like this?

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

as you might expect.

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 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 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, though there are a number of ways to manipulate that so as to make the representation more compact.

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.

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



来源:https://stackoverflow.com/questions/21027735/how-to-parse-ipv6-address-into-octets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!