Jingwei
Jingwei

Reputation: 115

InetAddress.getLocalHost() always returns 127.0.0.1

Anyone knows why InetAddress.getLocalHost() always returns 127.0.0.1 although I have changed the ip inside /etc/hosts? After the change

hostname -i

returns the correct ip (192.168.x.x), but InetAddress.getLocalHost() is still the name.

I'm using jdk 1.6.0_31 by the way, on CentOS 6.2. Thanks!

Upvotes: 6

Views: 5153

Answers (4)

Fanjita
Fanjita

Reputation: 393

An old question, but maybe this info will be helpful to someone else - I've struggled to find the information documented anywhere (maybe because it's not a formal part of the language spec), and had to determine via experimentation.

If the problem isn't down to the SecurityManager, then the most likely problem is that your name resolution at the OS level is screwed up somehow.

At least on all Unix platforms that I've tested on (OS X, Solaris, Linux), the process used by Java is:

  1. Determine local hostname
  2. Resolve that via /etc/hosts to determine IP address

I've seen this broken by badly-configured /etc/hosts, such as:

127.0.0.1 localhost myhost
1.2.3.4   myhost

to give exactly the symptoms described above.

Upvotes: 2

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

  1. First of all LocalHost will always represents the LoopBack address 127.0.0.1(which is used to debug the TCP/IP stack.) when Security manager founds that the operation is not allowed.

  2. For your LAN address use InetAddress.getByName("PC NAME").getHostAddress()

    Please replace PC NAME with your Pc Name.

Eg:

public class StrTest {


    public static void main(String[] args) throws IOException {


            System.out.println(InetAddress.getByName("Vicky-PC").getHostAddress());

    }

}

Upvotes: 0

Keppil
Keppil

Reputation: 46219

This could be a security restriction issue. From the javadoc:

If there is a security manager, its checkConnect method is called with the local host name and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress representing the loopback address is returned.

Upvotes: 1

niklas
niklas

Reputation: 153

because you have to restart your pc or clear dns cache to "apply" the changes

Upvotes: 1

Related Questions