6

I'm trying to write a simple program using Java that, given an IP in either version 4 or 6 format, will return its FQDN. The following code works fine when given an ipv4 address, but will only return the given address when an ipv6 address is entered.

InetAddress inet;
try { inet = InetAddress.getByName(theIpAddress); }
catch(UnknownHostException e) { System.out.println("Unknown Host"); return; }

System.out.println(inet.getHostAddress(););
System.out.println(inet.getHostName(););

Whenever I enter an ipv6 getHostName() will only return the same ipv6, even when I know that the ipv6 will resolve to a FQDN. Also, if I enter an ipv6 host name, such as ipv6.google.com, in place of theIpAddress, the exception will occur.

I'm new to this stuff so would appreciate any assistance. Thanks.

4

4 回答 4

2

问题实际上是我正在运行的 Java 版本。将 Java 从 1.6.21 更新到 1.6.23,允许 ipv6s 解析为其 FQDN。

于 2011-01-05T20:59:41.140 回答
2

我已经快速调查了 java 8、Windows 7 中主机名 <-> ipv6 解析的情况。看起来“默认”NameService 根本不适用于 ipv6!但!Java 附带了另一个名为“dns,sun”的基于 JNDI 的 NameService 实现。所以,如果你启用它使用

-Dsun.net.spi.nameservice.provider.1=dns,sun

或者

System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");

您将获得像这样的 v4 和 v6 地址的双向 ip <-> 主机名解析

InetAddress.getAllByName(...)
address.getHostName()

有关 java ipv6 的更多信息,您可以在此处找到http://docs.oracle.com/javase/8/docs/technotes/guides/net/ipv6_guide/

于 2015-11-17T16:12:43.060 回答
1

试试inet.getCanonicalHostName();“获取此 IP 地址的完全限定域名”。

如果您使用 , 构造 InetAddress InetAddress.getByName()getHostName()将返回您构造它的内容。 getCanonicalHostName()强制反向名称查找。

于 2011-01-03T23:52:25.470 回答
-2

使用java.net.InetAddress它是不可能有 ipv6 和 ipv4 名称解析等。像getByNameetc 这样的一堆静态方法将查找委托给它的Inet4(or 6)AddressImpl实例

public native InetAddress[] lookupAllHostAddr(String hostname) throws UnknownHostException;

现在有趣的是 a) 所有这些都是私有的/包本地的,因此无法将 impl 类注入 InetAddress 类 b) Inet4(或 6)AddressImpl 类本身是包本地的。所以没有办法说,即时进行 ipv4 或 ipv6 查找/名称解析。我不明白这些类的所有扩展点都被阻止的方式,这使得它们的使用和灵活性非常有限。真正的黑魔法发生在这里,InetAddress 类静态初始化 impls,方法 isIPv6Supported() 的结果依赖于什么?我的 Linux 设置支持 ipv6,我可以对 ipv6 主机名(如 ipv6.google.com)进行 dns 查找。如果有人能指出我在 java 中用于 ipv4/v6 实用程序(如查找等)的良好网络库的方向,将不胜感激。

class InetAddressImplFactory {

    static InetAddressImpl create() {
    Object o;
    if (isIPv6Supported()) {
        o = InetAddress.loadImpl("Inet6AddressImpl");
    } else {
        o = InetAddress.loadImpl("Inet4AddressImpl");
    }
    return (InetAddressImpl)o;
    }

    static native boolean isIPv6Supported();
}
于 2011-03-14T13:00:54.400 回答