InetAddress.getLocalHost() throws UnknownHostException

本文介绍了一个在OpenSolaris系统中使用Java应用程序遇到的UnknownHostException问题及其解决方案。问题出现在尝试获取本地主机名时,通过检查和修改/etc/hosts文件来解决此异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
}
The output is:

java.net.UnknownHostException: desvearth01: desvearth01
at java.net.InetAddress.getLocalHost(InetAddress.java:1353)
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?

Any hints appreciated, thanks.

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

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.

Above 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 helpfull for even naive users.

Steps:

Open /etc/hosts, the entries might look like below.
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
you need to add one more line above of this by any editor like vi or gedit.
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
Just save it and run again your java…code your work is done.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值