InetAddress.getHostAddress() ipv6 compliant?

孤人 提交于 2019-11-29 13:53:36

The extended class java.net.Inet6Address is IPv6 compliant.

JavaDoc:

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

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/Inet6Address respectively.

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

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

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

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

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!