java InetAddress.getHostAddress() 是否符合 ipv6?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6908398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
InetAddress.getHostAddress() ipv6 compliant?
提问by Fakrudeen
Is InetAddress.getHostAddress()ipv6 compliant in JDK 1.6?
是 InetAddress.getHostAddress()的IPv6兼容的JDK 1.6?
Specifically I am doing
具体我在做什么
InetAddress.getLocalHost().getHostAddress()
Is it ipv6 compliant? Does it work for both ipv4 and v6 addresses?
是否符合 ipv6?它对 ipv4 和 v6 地址都有效吗?
采纳答案by Fakrudeen
I looked at the code of InetAddress class and it is indeed doing the right thing.
我查看了 InetAddress 类的代码,它确实在做正确的事情。
if (isIPv6Supported()) {
o = InetAddress.loadImpl("Inet6AddressImpl");
}
else {
o = InetAddress.loadImpl("Inet4AddressImpl"); }
return (InetAddressImpl)o;
}
回答by Buhake Sindi
The extended class java.net.Inet6Address
is IPv6 compliant.
扩展类java.net.Inet6Address
符合 IPv6。
JavaDoc:
Java文档:
This class represents an Internet Protocol version 6 (IPv6) address. Defined by RFC 2373: IP Version 6 Addressing Architecture.
此类表示 Internet 协议版本 6 (IPv6) 地址。由 RFC 2373 定义:IP 版本 6 寻址架构。
Basically, if you do InetAddress.getByName()
or InetAddress.getByAddress()
the methods identify whether the name or address is an IPv4 or IPv6 name/address and return an extended Inet4Address
/Inet6Address
respectively.
基本上,如果您这样做InetAddress.getByName()
或InetAddress.getByAddress()
方法识别名称或地址是 IPv4 还是 IPv6 名称/地址并分别返回扩展的Inet4Address
/ Inet6Address
。
As for InetAddress.getHostAddress()
, it returns a null. You will need java.net.Inet6Address.getHostAddress()
to return an IPv6 string representable address.
至于InetAddress.getHostAddress()
,它返回一个null。您将需要java.net.Inet6Address.getHostAddress()
返回一个可表示的 IPv6 字符串地址。
回答by Srinu Yarru
Here is the code to test based on the above analysis:
下面是基于以上分析进行测试的代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
InetAddress localIP;
try {
localIP = InetAddress.getLocalHost();
if(localIP instanceof Inet6Address){
System.out.println("IPV6");
} else if (localIP instanceof Inet4Address) {
System.out.println("IPV4");
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}