InetAddress.getLocalHost() throws UnknownHostException

I use NetworkInterface.getNetworkInterfaces() as a fall back for when InetAddress.getLocalHost() throws an UnknownHostException. Here's the code (without exception handling for clarity).

Enumeration<NetworkInterface> iterNetwork;
Enumeration<InetAddress> iterAddress;
NetworkInterface network;
InetAddress address;

iterNetwork = NetworkInterface.getNetworkInterfaces();

while (iterNetwork.hasMoreElements())
{
   network = iterNetwork.nextElement();

   if (!network.isUp())
      continue;

   if (network.isLoopback())
      continue;

   iterAddress = network.getInetAddresses();

   while (iterAddress.hasMoreElements())
   {
      address = iterAddress.nextElement();

      if (address.isAnyLocalAddress())
         continue;

      if (address.isLoopbackAddress())
         continue;

      if (address.isMulticastAddress())
         continue;

      return address.getHostAddress();
   }
}

Other answers edit the /etc/hosts file. This is error prone, brittle, may require root access and won't work on all OS's.


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.


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.

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 (e.g. <your-machine-ip> <your-machine-name> 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
  • Just save it and run again your Java code... your work is done.