Is there a way in Java to tell it to return IPv6 only? I've tried everything and can't get it to work.
try
{
InetAddress inet = InetAddress.getByName(hostName);
boolean status = inet.isReachable(5000);
if (status)
{
System.out.println(inet.getCanonicalHostName() + " Host Reached\t" + java.net.Inet6Address.getByName(hostName).getHostAddress());
}
else
{
System.out.println(inet.getCanonicalHostName() + " Host Unreachable");
}
}
catch (UnknownHostException e)
{
System.err.println("Host does not exists");
}
catch (IOException e)
{
System.err.println("Error in reaching the Host");
}
The line I use to try to return IPv6 only:
System.out.println(inet.getCanonicalHostName() + " Host Reached\t" + java.net.Inet6Address.getByName(hostName).getHostAddress());
This keeps returning IPv4. Anyone have any idea of why its doing this?
java.net.Inet6Address
does not overridegetByName()
so it will always return the specific IPv4-Address, unless your parameter itself is in the form of an valid IPv6-Address, in this case this method will return an Inet6Address-Object.
For example:
getByName("stackoverflow.com")
--> Inet4AddressgetByName("2001:0db8:85a3:08d3:1319:8a2e:0370:7344")
--> Inet6AddressInetAddress.getByName()-Documentation
So if you want to get an IPv6-Address you need to define it within your parameter, or configure a DNS-Server to return the IPv6-Address instead of the IPv4-Address.
Another way to retrieve the IPv6-Address is using
InetAddress.getAllByName("www.google.at")
which returns all known IP-Addresses of the host.For example you can use this method to filter the returned array, which return the first IPv6-Address or
null
if the host don't have one:UPDATE: For more functions, especially those affecting DNS-Servers, I recommend using the external library DNSJava, because the plain Java implementation of DNS support is poor.
http://www.dnsjava.org/
Current Code:
You could try to define JVM_ARGS
-Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=true
with that props it will prefer IPv6 addr on
InetAddress#getByName
More info: https://docs.oracle.com/javase/8/docs/technotes/guides/net/ipv6_guide/