1

InetAddress.getLocalHost() throws unknownHostException in linux until I manually add entry in /etc/hosts. Is there any way to get InetAddress object without add an entry in /etc/host file.. Note : The IP is static

suresh
  • 4,084
  • 10
  • 44
  • 59
  • http://www.velocityreviews.com/forums/t133268-getlocalhost.html Looks like the Java libs are trying to get an externally-applicable _name_ for the machine, and then look up that name. Seems silly to me, as a machine may have none or millions of correct externally-applicable names, and IP addresses come and go... Why do you want to use this routine? Perhaps there's a better choice of API for your problem. – sarnold Jul 19 '10 at 10:29
  • @sarnold. What is the better choice of API for this probelm? – suresh Jul 27 '10 at 10:00

2 Answers2

2
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();
                    }
                  }
user395752
  • 21
  • 1
0

I am wondering the same thing. In this post, I have a machine where I did NOT add an entry into /etc/hosts...

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

but I think that machine is maybe configured differently, but not sure how. I prefer not having to add it to /etc/hosts as we already configured the hostname in /etc/sysconfig/network and one place "should" be enough.

Community
  • 1
  • 1
Dean Hiller
  • 19,235
  • 25
  • 129
  • 212