Java. InetAddress.getLocalHost returns strange IP

百般思念 提交于 2019-12-10 14:29:53

问题


I'm don't understand, why code below prints 0.0.9.229 instead 127.0.0.1. Can anybody tell me, hot to fix that?

String ha = InetAddress.getLocalHost().getHostAddress();
System.out.println(ha);

UPD: Code running on Ubuntu

/etc/hosts

127.0.0.1       localhost
127.0.1.1       2533

回答1:


InetAddress.getLocalHost() doesn't do what most people think that it does. It actually returns the hostname of the machine, and the IP address associated with that hostname. This may be the address used to connect to the outside world. It may not. It just depends on how you have your system configured.

On my windowsbox it gets the machine name and the external ip address. On my linux box it returns hostname and 127.0.0.1 because I have it set so in /etc/hosts




回答2:


The problem is that my hostname will consists only of numbers and could not be resolved. I change my /etc/hostname with characters at first position and problem has solved.




回答3:


Use NetworkInterface to enumerate network interfaces; InetAddress.getLocalHost() always returns loopback.If you want to get all IP's associated with your machine use NetworkInterface then you will get 127.0.0.1 also.

 Enumeration<NetworkInterface> nInterfaces = NetworkInterface.getNetworkInterfaces();

    while (nInterfaces.hasMoreElements()) {
        Enumeration<InetAddress> inetAddresses = nInterfaces.nextElement().getInetAddresses();
        while (inetAddresses.hasMoreElements()) {
            String address = inetAddresses.nextElement().getHostAddress();
            System.out.println(address);
        }
    }


来源:https://stackoverflow.com/questions/18488809/java-inetaddress-getlocalhost-returns-strange-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!