Force InetAddress.getHostAddress() to return IPv4

2019-06-26 05:48发布

问题:

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

回答1:

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.



标签: java ipv6 ipv4