简体   繁体   中英

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.xx), but InetAddress.getLocalHost() is still the name.

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

因为您必须重新启动电脑或清除DNS缓存以“应用”更改

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.

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.

  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());

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM