【问题标题】:InetAddress.getLocalHost() throws unknownHostException in linuxInetAddress.getLocalHost() 在 linux 中抛出 unknownHostException
【发布时间】:2010-07-19 10:20:06
【问题描述】:

InetAddress.getLocalHost() 在 linux 中抛出 unknownHostException,直到我在 /etc/hosts 中手动添加条目。有什么方法可以在不添加 /etc/host 文件中的条目的情况下获取 InetAddress 对象。注意:IP 是静态的

【问题讨论】:

  • velocityreviews.com/forums/t133268-getlocalhost.html 看起来 Java 库正在尝试为机器获取一个外部适用的 name,然后查找该名称。对我来说似乎很愚蠢,因为一台机器可能没有或数百万个正确的外部适用名称,而且 IP 地址来来去去......你为什么要使用这个例程?对于您的问题,也许有更好的 API 选择。
  • @sarnold。对于这个问题,API 的更好选择是什么?

标签: java linux


【解决方案1】:
String host = null;
NetworkInterface iface = null;

        for(Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();ifaces.hasMoreElements();){
                   iface = (NetworkInterface)ifaces.nextElement();
                   InetAddress ia = null;
                    for(Enumeration<InetAddress> ips = iface.getInetAddresses();ips.hasMoreElements();){
                    ia = (InetAddress)ips.nextElement();
                    if(!ia.isLoopbackAddress() && (!ia.isLinkLocalAddress()) && (ia instanceof Inet4Address)) host=ia.getHostAddress();
                    }
                  }

【讨论】:

    【解决方案2】:

    我也在想同样的事情。在这篇文章中,我有一台机器,我没有在 /etc/hosts 中添加条目...

    java getLocalHost() UnknownHostException /etc/hosts file differs linux api?

    但我认为这台机器的配置可能不同,但不确定如何。我不想将它添加到 /etc/hosts,因为我们已经在 /etc/sysconfig/network 中配置了主机名,一个地方“应该”就足够了。

    【讨论】:

      猜你喜欢
      • 2010-12-25
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 2023-03-18
      • 2017-07-23
      • 1970-01-01
      • 2018-06-20
      • 2019-05-01
      相关资源
      最近更新 更多