【问题标题】:How do I extract the prefix (/64) of an ipv6 address in C#?如何在 C# 中提取 ipv6 地址的前缀 (/64)?
【发布时间】:2013-11-18 09:02:06
【问题描述】:

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

【问题讨论】:

  • 我在你的例子中没有看到 /64....只是很多吻!
  • 哈哈。那些当然不是亲吻。将其视为 ipv6 全球单播地址。类似“1234:1234:1234:1234:1234:1234:1234:1234”的东西。那么,给定这个示例作为 c# 中的 IPAddress 对象,提取网络前缀的有效方法是什么? (恰好是 /64 部分)

标签: c# ipv6


【解决方案1】:

当您说 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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    相关资源
    最近更新 更多