Is InetAddress.getHostAddress () compatible with ipv6?

Is InetAddress.getHostAddress () compatible with ipv6 in JDK 1.6?

In particular, I do

InetAddress.getLocalHost().getHostAddress() 

Is ipv6 compatible? Does it work for ipv4 and v6 addresses?

+6
source share
3 answers

I looked at the code of the InetAddress class and it really does the right thing.

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

The java.net.Inet6Address extended class is compatible with IPv6.

JavaDoc:

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

Basically, if you execute InetAddress.getByName() or InetAddress.getByAddress() , the methods determine whether the name or address is the IPv4 or IPv6 name / address and return the extended Inet4Address / Inet6Address respectively.

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

+6
source

Here is the testing code 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(); } } 
+1
source

Source: https://habr.com/ru/post/894092/


All Articles