InetAddress.getLocalHost () always returns 127.0.0.1

Does anyone know why InetAddress.getLocalHost () always returns 127.0.0.1, although I changed the ip inside / etc / hosts? After change

hostname -i

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

I am using jdk 1.6.0_31, by the way, on CentOS 6.2. Thank!

+5
source share
4 answers

because you need to restart your computer or clear the DNS cache in order to "apply" the changes

+1
source

This may be a security limitation problem. From javadoc :

, checkConnect -1 , , . , InetAddress, .

+1

, , , - - , - (, ), .

SecurityManager, , - .

Unix, (OS X, Solaris, Linux), , Java:

  • Specify that through / etc / hosts determine the IP address

I saw this broken by badly configured / etc / hosts, for example:

127.0.0.1 localhost myhost
1.2.3.4   myhost

to give the symptoms described above exactly.

+1
source
  • First of all, LocalHost will always represent the LoopBack address 127.0.0.1 (which is used to debug the TCP / IP stack.) When the security manager detects that the operation is not allowed.

  • For your network address use InetAddress.getByName("PC NAME").getHostAddress()

    Please replace the PC name with your PC name.

For instance:

public class StrTest {


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


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

    }

}
0
source

All Articles