【问题标题】:Best way to check if IPv6 is available检查 IPv6 是否可用的最佳方法
【发布时间】:2012-04-13 13:22:24
【问题描述】:

检查当前安卓手机是否支持 IPv6 的最佳方法是什么?

我目前的想法是使用NetworkInterface 并通过NetworkInterface.getNetworkInterfaces() 进行枚举,但这似乎太复杂了。

有没有更简单的方法?

【问题讨论】:

    标签: android ipv6


    【解决方案1】:

    如果您需要检查所有接口,我不知道比使用NetworkInterface 更简单的方法,但应该没那么糟糕:

    for(NetworkInterface netInt: NetworkInterface.getNetworkInterfaces()){
        for(InterfaceAddress address: netInt.getInterfaceAddresses()){
            if(address.getAddress() instanceof Inet6Address){
                // found IPv6 address
                // do any other validation of address you may need here
            }
        }
    }
    

    如果您知道要检查的地址,则可以使用NetworkInterface 跳过并通过调用InetAddress 的静态getBy...() 方法之一检查特定的InetAddress,并检查这是否是@987654329 的实例@。

    【讨论】:

    • 这只有在设备当前连接到 ipv6 网络时才有效,对吗?
    • 这只会告诉你你有一个 IPv6 适配器。如果您在仅 IPv4 网络下游的 NAT64 网络上,这将假定您具有 IPv6 连接,但当您尝试建立 IPv6 连接时它将失败。
    【解决方案2】:
    boolean isIPV6 = false;
    Enumeration<NetworkInterface> networkInterfaces =
        NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
        NetworkInterface ni = networkInterfaces.nextElement();
        for (InterfaceAddress addr : ni.getInterfaceAddresses()) {
            if (addr.getAddress() instanceof Inet6Address) {
                isIPV6 = true;
            }
        }
    }
    

    【讨论】:

    • 为什么这个解决方案应该比公认的更好?您忘记在答案中写任何文档。
    • NetworkInterface.getNetworkInterfaces() 返回一个枚举,因此您不能 foreach 它,您需要像使用 Iterator&lt;NetworkInterface&gt; 一样使用它。除此之外,它基本上是相同的答案。我的只是编译。 :-P
    猜你喜欢
    • 1970-01-01
    • 2012-04-07
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2010-09-29
    • 2012-05-23
    相关资源
    最近更新 更多