InetAddress.getLocalHost() 抛出 UnknownHostException [英] InetAddress.getLocalHost() throws UnknownHostException

查看:34
本文介绍了InetAddress.getLocalHost() 抛出 UnknownHostException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在不同的操作系统上测试我们的服务器应用程序(编写的 Java),并认为 OpenSolaris (2008.11) 将是最不麻烦的,因为它具有良好的 Java 集成.结果我错了,因为我最终遇到了 UnknownHostException

I am testing our server-application (written Java) on different operating systems and thought that OpenSolaris (2008.11) would be the least troublesome due to the nice Java integration. Turns out I was wrong, as I end up with a UnknownHostException

try {
  computerName = InetAddress.getLocalHost().getHostName();
  if (computerName.indexOf(".") > -1)
    computerName = computerName.substring(0,
        computerName.indexOf(".")).toUpperCase();
} catch (UnknownHostException e) {
  e.printStackTrace();
}

输出为:

java.net.UnknownHostException: desvearth01: desvearth01
    at java.net.InetAddress.getLocalHost(InetAddress.java:1353)

但是,nslookup desvearth01 返回了正确的 IP 地址,而 nslookup localhost 会按预期返回 127.0.0.1.此外,相同的代码在 FreeBSD 上也能完美运行.OpenSolaris 有什么我不知道的特别之处吗?

However, nslookup desvearth01 returns the correct IP address, and nslookup localhost returns 127.0.0.1 as expected. Also, the same code works perfectly on FreeBSD. Is there anything special to OpenSolaris that I am not aware of?

感谢任何提示,谢谢.

推荐答案

按照传统,我可以再次回答我自己的问题:

In good tradition, I can answer my own question once again:

似乎InetAddress.getLocalHost()忽略了/etc/resolv.conf,而只看/etc/hosts文件(除了 localhost 之外,我没有指定任何内容).将 IP 和主机名添加到此文件中即可解决问题,异常消失.

It seems that InetAddress.getLocalHost() ignores the /etc/resolv.conf, but only looks at the /etc/hosts file (where I hadn't specified anything besides localhost). Adding the IP and hostname to this file solves the problem and the exception is gone.

另一个答案几乎是正确的,我从上面得到了提示,我的问题得到了解决......谢谢.

Another answer is almost correct and I got hint from above and my problem get resolved...Thanks.

但为了改进这一点,我正在添加分步更改,以便即使是天真的用户也会有所帮助.

But to improve this, I am adding steps-by-steps changes, so that it will be helpful for even naive users.

步骤:

  • 打开/etc/hosts,条目可能如下所示.

 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4  
 ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

  • 您需要通过任何编辑器(例如 ),例如 vigedit(例如 <your-machine-ip><您的机器名称> localhost).

     192.168.1.73 my_foo localhost
    

  • 现在,整个文件可能如下所示:

    Now, overall file may look like this:

    192.168.1.73 my_foo localhost
    127.0.0.1    localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1          localhost localhost.localdomain localhost6 localhost6.localdomain6
    

    • 只需保存并再次运行您的 Java 代码……您的工作就完成了.
    • 这篇关于InetAddress.getLocalHost() 抛出 UnknownHostException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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