java InetAddress.getHostAddress() 是否符合 ipv6?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6908398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:51:47  来源:igfitidea点击:

InetAddress.getHostAddress() ipv6 compliant?

javaipv6

提问by Fakrudeen

Is InetAddress.getHostAddress()ipv6 compliant in JDK 1.6?

InetAddress.getHostAddress()的IPv6兼容的JDK 1.6?

Specifically I am doing

具体我在做什么

InetAddress.getLocalHost().getHostAddress()

Is it ipv6 compliant? Does it work for both ipv4 and v6 addresses?

是否符合 ipv6?它对 ipv4 和 v6 地址都有效吗?

采纳答案by Fakrudeen

I looked at the code of InetAddress class and it is indeed doing the right thing.

我查看了 InetAddress 类的代码,它确实在做正确的事情。

  if (isIPv6Supported()) { 
      o = InetAddress.loadImpl("Inet6AddressImpl"); 
  } 
  else { 
      o = InetAddress.loadImpl("Inet4AddressImpl"); } 
      return (InetAddressImpl)o; 
  }

回答by Buhake Sindi

The extended class java.net.Inet6Addressis IPv6 compliant.

扩展类java.net.Inet6Address符合 IPv6。

JavaDoc:

Java文档:

This class represents an Internet Protocol version 6 (IPv6) address. Defined by RFC 2373: IP Version 6 Addressing Architecture.

此类表示 Internet 协议版本 6 (IPv6) 地址。由 RFC 2373 定义:IP 版本 6 寻址架构。

Basically, if you do InetAddress.getByName()or InetAddress.getByAddress()the methods identify whether the name or address is an IPv4 or IPv6 name/address and return an extended Inet4Address/Inet6Addressrespectively.

基本上,如果您这样做InetAddress.getByName()InetAddress.getByAddress()方法识别名称或地址是 IPv4 还是 IPv6 名称/地址并分别返回扩展的Inet4Address/ Inet6Address

As for InetAddress.getHostAddress(), it returns a null. You will need java.net.Inet6Address.getHostAddress()to return an IPv6 string representable address.

至于InetAddress.getHostAddress(),它返回一个null。您将需要java.net.Inet6Address.getHostAddress()返回一个可表示的 IPv6 字符串地址。

回答by Srinu Yarru

Here is the code to test based on the above analysis:

下面是基于以上分析进行测试的代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    InetAddress localIP;
    try {
        localIP = InetAddress.getLocalHost();
         if(localIP instanceof Inet6Address){
             System.out.println("IPV6");
         } else if (localIP instanceof Inet4Address) {
             System.out.println("IPV4");
         }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

}