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

2
  • 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. Commented Jul 19, 2010 at 10:29
  • @sarnold. What is the better choice of API for this probelm? Commented Jul 27, 2010 at 10:00

2 Answers 2

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();
                    }
                  }
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.