如何在C#中提取ipv6地址的前缀(/ 64)?

时间:2013-11-18 09:02:07

标签: c# ipv6

给定ipv6地址,如“xxxx:xxxx:xxxx:xx:xxxx:xxxx:xxxx:xxxx”,如何在C#中提取前缀部分(/ 64)。

1 个答案:

答案 0 :(得分:0)

当您说Given an ipv6 address时,我假设您有一个类型为IPAddress的对象,其中包含您的IPv6地址。

根据IPAddress的上述链接文档,它有一个方法GetAddressBytes,它为您提供包含存储地址的所有字节的byte[]。现在,给定您的前缀(/ 64)并知道1字节= 8位,我们可以构造以下内容:

//using System.Net

IPAddress address; //I assume it is initialized correctly
int prefix = 64;

//check if it is an IPv6-address
if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
  //and copy the prefix-bytes
  byte[] prefixBytes = new byte[prefix/8];
  Array.Copy(address.GetAddressBytes(), prefixBytes, prefix/8);
  //now the array contains the (in this example 8) prefix bytes
}

对于简单的可视化测试,您可以将其打印到控制台:

for (int i = 0; i < prefixBytes.Length; i++)
{
  if (i % 2 == 0 && i != 0)
    Console.Write(":");

  Console.Write(prefixBytes[i].ToString("X2").ToLower());
}