Force InetAddress.getHostAddress() to return IPv4 address

耗尽温柔 提交于 2019-12-23 12:37:58

问题


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.



来源:https://stackoverflow.com/questions/14282608/force-inetaddress-gethostaddress-to-return-ipv4-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!