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

问题描述 投票:-3回答:1

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

c# ipv6
1个回答
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());
}
© www.soinside.com 2019 - 2024. All rights reserved.