6

I'm using a library that uses java.net.InetAddress.getLocalHost().getHostAddress() to get my local IP address. However, this always returns an IPv6 address on my computer (Gentoo Linux, JDK 1.6.0_37). The address is further used in a context which does not support IPv6 addresses and thus fails.

Is there some way to force getHostAddress() to return a IPv4 address (e.g. through a parameter to JVM)?

Bob
  • 5,510
  • 9
  • 48
  • 80
  • [Get your IP address in java](http://stackoverflow.com/a/9482369/1135954) might be useful. – mtk Jan 11 '13 at 16:40
  • Thanks, but I want to avoid changing my source code because the call is within a library which I don't want to change. – Bob Jan 11 '13 at 16:41

1 Answers1

9

You can set it to use IPv4 when avaiable. Of course, there are a great number more IPv6 address than IPv4 addresses, so it certainly doesn't guarantee always getting an IPv4 address.

java.net.preferIPv4Stack = true

Either set with:

System.setProperty("java.net.preferIPv4Stack" , "true");

Or as a command line arg:

-Djava.net.preferIPv4Stack=true

Preference for IPv4 addresses is generally default behavior anyway, though.

If you need to ensure that you Never get an IPv6 address, I think you would need to check that java.net.InetAddress.getLocalHost().getHostAddress() does not return an Inet6Address, and handle it if it does (as an exception, I suppose).

Either that or, of course, the better way: fix your code to support IPv6.

femtoRgon
  • 32,893
  • 7
  • 60
  • 87