如何判断IPv6地址是否私有?

2024-02-14

我试图确定给定的 IPv6 地址在 C# 中是否是私有的,并且我很想简单地使用 IPAddress 类上的“IsIPv6SiteLocal”属性。然而,正如本节中所解释的comment https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress/6461537#6461537,此属性中实现的逻辑已被弃用。我运行了以下单元测试:

[TestMethod]
public void IsPrivate_ipv6_True()
{
    // This sample private IPv6 address was generated using: http://unique-local-ipv6.com/
    var ip = IPAddress.Parse("fd44:fda4:e1ba::1");
    Assert.IsTrue(ip.IsIPv6SiteLocal);
}

单元测试中的断言失败,这确认 IsIPv6SiteLocal 无法正确确定地址是否为本地地址。所以我需要一个替代方案。

我编写了以下扩展方法,我想知道是否有人能想到一种无法正确确定地址是私有/公共的场景。

public static bool IsPrivateIPv6(this IPAddress address)
{
    var addressAsString = address.ToString();
    var firstWord = addressAsString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[0];

    // Make sure we are dealing with an IPv6 address
    if (address.AddressFamily != AddressFamily.InterNetworkV6) return false;

    // The original IPv6 Site Local addresses (fec0::/10) are deprecated. Unfortunately IsIPv6SiteLocal only checks for the original deprecated version:
    else if (address.IsIPv6SiteLocal) return true;

    // These days Unique Local Addresses (ULA) are used in place of Site Local. 
    // ULA has two variants: 
    //      fc00::/8 is not defined yet, but might be used in the future for internal-use addresses that are registered in a central place (ULA Central). 
    //      fd00::/8 is in use and does not have to registered anywhere.
    else if (firstWord.Substring(0, 2) == "fc" && firstWord.Length >= 4) return true;
    else if (firstWord.Substring(0, 2) == "fd" && firstWord.Length >= 4) return true;

    // Link local addresses (prefixed with fe80) are not routable
    else if (firstWord == "fe80") return true;

    // Discard Prefix
    else if (firstWord == "100") return true;

    // Any other IP address is not Unique Local Address (ULA)
    else return false;
}

2016 年 2 月 13 日编辑:

  • 确保第一个单词的长度至少为 4 个字符(按照@RonMaupin 的建议)
  • 按照 @RonMaupin 的建议改进了“else return false”上面的评论
  • 检查 @KevinBurdett 建议的“fe80”前缀
  • 按照 @KevinBurdett 的建议检查“丢弃”前缀

通过添加特殊情况改进了 @desautelsj 的答案::1并避免他的解决方案中出现 ArgumentException (这会发生在Substring() call):

public static bool IsPrivateIPv6(IPAddress address)
{
    // Make sure we are dealing with an IPv6 address
    if (address.AddressFamily != AddressFamily.InterNetworkV6)
        throw new ArgumentException("IP address is not V6", "address");

    var addressAsString = address.ToString();
    var firstWord = addressAsString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[0];

    // equivalent of 127.0.0.1 in IPv6
    if (addressAsString == "::1")
        return true;

    // The original IPv6 Site Local addresses (fec0::/10) are deprecated. Unfortunately IsIPv6SiteLocal only checks for the original deprecated version:
    else if (address.IsIPv6SiteLocal)
        return true;

    // These days Unique Local Addresses (ULA) are used in place of Site Local. 
    // ULA has two variants: 
    //      fc00::/8 is not defined yet, but might be used in the future for internal-use addresses that are registered in a central place (ULA Central). 
    //      fd00::/8 is in use and does not have to registered anywhere.
    else if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fc")
        return true;
    else if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fd")
        return true;

    // Link local addresses (prefixed with fe80) are not routable
    else if (firstWord == "fe80")
        return true;

    // Discard Prefix
    else if (firstWord == "100")
        return true;

    // Any other IP address is not Unique Local Address (ULA)
    return false;
}

在 F# 中:

let private IsIpv6AddressPrivate (address: IPAddress) =
    if address.AddressFamily = AddressFamily.InterNetwork then
        invalidArg "address" "address must be IPv6"

    // The original IPv6 Site Local addresses (fec0::/10) are deprecated. Unfortunately IsIPv6SiteLocal only checks for the original deprecated version:
    elif address.IsIPv6SiteLocal then
        true
    else
        let addressAsString = address.ToString()

        // equivalent of 127.0.0.1 in IPv6
        if addressAsString = "::1" then
            true
        else
            let firstWord = addressAsString.Split([|':'|], StringSplitOptions.RemoveEmptyEntries).[0]
            // These days Unique Local Addresses (ULA) are used in place of Site Local. 
            // ULA has two variants: 
            //      fc00::/8 is not defined yet, but might be used in the future for internal-use addresses that are registered in a central place (ULA Central). 
            //      fd00::/8 is in use and does not have to registered anywhere.
            if (firstWord.Length >= 4 && firstWord.Substring(0, 2) = "fc") ||
               (firstWord.Length >= 4 && firstWord.Substring(0, 2) = "fd") ||
               // Link local addresses (prefixed with fe80) are not routable
               (firstWord = "fe80") ||
               // Discard Prefix
               (firstWord = "100") then
                true
            else
                false
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何判断IPv6地址是否私有? 的相关文章

  • 在一个数据访问层中处理多个连接字符串

    我有一个有趣的困境 我目前有一个数据访问层 它必须与多个域一起使用 并且每个域都有多个数据库存储库 具体取决于所调用的存储过程 目前 我只需使用 SWITCH 语句来确定应用程序正在运行的计算机 并从 Web config 返回适当的连接字
  • C++11 删除重写方法

    Preface 这是一个关于最佳实践的问题 涉及 C 11 中引入的删除运算符的新含义 当应用于覆盖继承父类的虚拟方法的子类时 背景 根据标准 引用的第一个用例是明确禁止调用某些类型的函数 否则转换将是隐式的 例如最新版本第 8 4 3 节
  • std::vector 与 std::stack

    有什么区别std vector and std stack 显然 向量可以删除集合中的项目 尽管比列表慢得多 而堆栈被构建为仅后进先出的集合 然而 堆栈对于最终物品操作是否更快 它是链表还是动态重新分配的数组 我找不到关于堆栈的太多信息 但
  • 如何从本机 C(++) DLL 调用 .NET (C#) 代码?

    我有一个 C app exe 和一个 C my dll my dll NET 项目链接到本机 C DLL mynat dll 外部 C DLL 接口 并且从 C 调用 C DLL 可以正常工作 通过使用 DllImport mynat dl
  • -webkit-box-shadow 与 QtWebKit 模糊?

    当时有什么方法可以实现 webkit box shadow 的工作模糊吗 看完这篇评论错误报告 https bugs webkit org show bug cgi id 23291 我认识到这仍然是一个问题 尽管错误报告被标记为RESOL
  • 无限循环与无限递归。两者都是未定义的吗?

    无副作用的无限循环是未定义的行为 看here https coliru stacked crooked com view id 24e0a58778f67cd4举个例子参考参数 https en cppreference com w cpp
  • 如何使从 C# 调用的 C(P/invoke)代码“线程安全”

    我有一些简单的 C 代码 它使用单个全局变量 显然这不是线程安全的 所以当我使用 P invoke 从 C 中的多个线程调用它时 事情就搞砸了 如何为每个线程单独导入此函数 或使其线程安全 我尝试声明变量 declspec thread 但
  • 访问外部窗口句柄

    我当前正在处理的程序有问题 这是由于 vista Windows 7 中增强的安全性引起的 特别是 UIPI 它阻止完整性级别较低的窗口与较高完整性级别的窗口 对话 就我而言 我想告诉具有高完整性级别的窗口进入我们的应用程序 它在 XP 或
  • 重载 (c)begin/(c)end

    我试图超载 c begin c end类的函数 以便能够调用 C 11 基于范围的 for 循环 它在大多数情况下都有效 但我无法理解和解决其中一个问题 for auto const point fProjectData gt getPoi
  • 人脸 API DetectAsync 错误

    我想创建一个简单的程序来使用 Microsoft Azure Face API 和 Visual Studio 2015 检测人脸 遵循 https social technet microsoft com wiki contents ar
  • C# - 当代表执行异步任务时,我仍然需要 System.Threading 吗?

    由于我可以使用委托执行异步操作 我怀疑在我的应用程序中使用 System Threading 的机会很小 是否存在我无法避免 System Threading 的基本情况 只是我正处于学习阶段 例子 class Program public
  • 两个类可以使用 C++ 互相查看吗?

    所以我有一个 A 类 我想在其中调用一些 B 类函数 所以我包括 b h 但是 在 B 类中 我想调用 A 类函数 如果我包含 a h 它最终会陷入无限循环 对吗 我能做什么呢 仅将成员函数声明放在头文件 h 中 并将成员函数定义放在实现文
  • LINQ:使用 INNER JOIN、Group 和 SUM

    我正在尝试使用 LINQ 执行以下 SQL 最接近的是执行交叉联接和总和计算 我知道必须有更好的方法来编写它 所以我向堆栈团队寻求帮助 SELECT T1 Column1 T1 Column2 SUM T3 Column1 AS Amoun
  • C# 动态/expando 对象的深度/嵌套/递归合并

    我需要在 C 中 合并 2 个动态对象 我在 stackexchange 上找到的所有内容仅涵盖非递归合并 但我正在寻找能够进行递归或深度合并的东西 非常类似于jQuery 的 extend obj1 obj2 http api jquer
  • 为什么 isnormal() 说一个值是正常的,而实际上不是?

    include
  • 如何在 Linq to SQL 中使用distinct 和 group by

    我正在尝试将以下 sql 转换为 Linq 2 SQL select groupId count distinct userId from processroundissueinstance group by groupId 这是我的代码
  • 如何在 Android 中使用 C# 生成的 RSA 公钥?

    我想在无法假定 HTTPS 可用的情况下确保 Android 应用程序和 C ASP NET 服务器之间的消息隐私 我想使用 RSA 来加密 Android 设备首次联系服务器时传输的对称密钥 RSA密钥对已在服务器上生成 私钥保存在服务器
  • C# 中的 IPC 机制 - 用法和最佳实践

    不久前我在 Win32 代码中使用了 IPC 临界区 事件和信号量 NET环境下场景如何 是否有任何教程解释所有可用选项以及何时使用以及为什么 微软最近在IPC方面的东西是Windows 通信基础 http en wikipedia org
  • 当文件流没有新数据时如何防止fgets阻塞

    我有一个popen 执行的函数tail f sometextfile 只要文件流中有数据显然我就可以通过fgets 现在 如果没有新数据来自尾部 fgets 挂起 我试过ferror and feof 无济于事 我怎样才能确定fgets 当
  • 为什么 std::uint32_t 与 uint32_t 不同?

    我对 C 有点陌生 我有一个编码作业 很多文件已经完成 但我注意到 VS2012 似乎有以下语句的问题 typedef std uint32 t identifier 不过 似乎将其更改为 typedef uint32 t identifi

随机推荐