Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force InetAddress.getHostAddress() to return IPv4 address

Tags:

java

ipv6

ipv4

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)?

like image 463
Bob Avatar asked Jan 11 '13 16:01

Bob


1 Answers

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.

like image 190
femtoRgon Avatar answered Oct 23 '22 11:10

femtoRgon