Sunday, October 14, 2012

MAC OS X - InetAddress.getLocalHost() throws UnknownHostException

I am currently looking at some socket programming code which works in windows, but not in MAC OS X 10.7. I am using JDK 1.7. Previously this worked well in JDK 1.6.

The issue is with InetAddress.getLocalHost()
it throws java.net.UnknownHostException when I used with getHostAddress or getHostName.

The workaround is, edit host files.

Open Terminal and type the line shown below to edit in etc/hosts.
sudo nano /private/etc/hosts

Enter password.

In etc/hosts, (use arrow keys to move around) add a new line with  IP address <space> and hostname

Here, you can get the hostname by typing 'hostname' in terminal

To save control+o, then enter and to exit control+x

Now back in terminal, flush the cache by
dscacheutil -flushcache

Now, there should not be any error.

Sometimes you get both hostname and IP with getLocalHost(). Therefore, from getLocalhost() extract only the substring with the IP.

Steps are:

  1. First convert the inetAddress you get with getLocalHost to String. 
  2. Then get the substring with the IP (Original String will be in the form of <host_name>/<IP>) e.g. String ip_addr
  3. Convert back the IP substring to inetAddress to be used in Socket. InetAddress.getName(ip_addr)

More information @ http://java.net/jira/browse/MACOSX_PORT-564

1 comment:

  1. My Experience...: Mac Os X - Inetaddress.Getlocalhost() Throws Unknownhostexception >>>>> Download Now

    >>>>> Download Full

    My Experience...: Mac Os X - Inetaddress.Getlocalhost() Throws Unknownhostexception >>>>> Download LINK

    >>>>> Download Now

    My Experience...: Mac Os X - Inetaddress.Getlocalhost() Throws Unknownhostexception >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete