强制InetAddress.getHostAddress()返回IPv4地址 [英] Force InetAddress.getHostAddress() to return IPv4 address

查看:55
本文介绍了强制InetAddress.getHostAddress()返回IPv4地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用使用java.net.InetAddress.getLocalHost().getHostAddress()来获取我的本地IP地址的库.但是,这总是在我的计算机(Gentoo Linux,JDK 1.6.0_37)上返回IPv6地址.该地址还会在不支持IPv6地址的上下文中使用,因此会失败.

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.

是否有某种方法可以强制getHostAddress()返回IPv4地址(例如,通过JVM的参数)?

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

推荐答案

您可以将其设置为在可用时使用IPv4.当然,IPv6地址比IPv4地址多得多,因此,它当然不能保证始终获得IPv4地址.

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

设置为:

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

或作为命令行arg:

-Djava.net.preferIPv4Stack=true

尽管如此,对IPv4地址的偏好通常还是默认行为.

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

如果您需要确保从不获取IPv6地址,我认为您需要检查java.net.InetAddress.getLocalHost().getHostAddress()不返回Inet6Address,并对其进行处理(我想是例外).

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

或者,或者当然是更好的方法:修复代码以支持IPv6.

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

这篇关于强制InetAddress.getHostAddress()返回IPv4地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆