Skip to content

Instantly share code, notes, and snippets.

@WhyNotHugo
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WhyNotHugo/319ce21a26fb4594e2e2 to your computer and use it in GitHub Desktop.
Save WhyNotHugo/319ce21a26fb4594e2e2 to your computer and use it in GitHub Desktop.
Example of how to enable IPv6 only after testing if it works
package test;
import java.lang.reflect.Field;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* This sample code shows how to determine if there is IPv6 connectivity, and
* alters java properties to enable IPv6 again if it works. This works with
* "-Djava.net.preferIPv6Address=false, and the goal is to not interfere with
* applications that currently prefer IPv4 for some reason.
*
* @author hugo
*
*/
public class Test {
/**
* Enables IPv6 only if it works. Returns true if IPv6 was enabled. Upon any
* sort of error will bail and not change anything.
*/
public static boolean enableIPv6OnlyIfItWorks() {
try {
// This flag is set to true after an IPv6 connection was
// established.
boolean ipv6Works = false;
// Temporarily undo this setting. Altering preferIPv6Address will
// suffice
System.setProperty("java.net.preferIPv4Stack", "false");
for (InetAddress addr : InetAddress.getAllByName("hugo.barrera.io")) {
// InetAddress#isReachable would fail in some special scenarios
// (ie: filtered ICMP)
if (addr instanceof Inet4Address)
continue;
if (addr instanceof Inet6Address) {
new Socket(addr, 80);
ipv6Works = true;
}
}
// Set preferIPv6Address according to our results:
Field f = InetAddress.class.getDeclaredField("preferIPv6Address");
f.setAccessible(true);
f.set(null, ipv6Works);
return true;
} catch (Exception e) {
// Catching Exception isn't generally a good idea, but in this
// scenario we want to bail regardless of what the error was. The
// purpose is to not add any new possible points of failure.
System.setProperty("java.net.preferIPv4Stack", "true");
System.err
.println("Something went wrong while testing or configuring IPv6.");
System.err.println("Settings were not altered.");
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws UnknownHostException {
// The sample code will work even if this property is set to false:
System.setProperty("java.net.preferIPv6Address", "false");
enableIPv6OnlyIfItWorks();
System.out.println(InetAddress.getByName("elysion.barrera.io"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment