IP Address not obtained in java

前端 未结 5 1106
北海茫月
北海茫月 2020-12-05 14:26

This code used to return my local ip address as 192.xxx.x.xxx but now it is returning 127.0.0.1 . Please help me why the same code is returning different value. Is there som

5条回答
  •  一整个雨季
    2020-12-05 15:01

    This is because you have a line in /etc/hosts like 127.0.0.1 localhost you need to have 192.xxx.xxx.xxx localhost

    Though please note that this would be very bad as to solve a code issue you should not modify linux config files. Not only is it not right (and risks breaking some other network aware apps on your linux box) it will also not work anywhere else (unless the admins of those boxes are also like minded).

    javadoc for InetAddress.getLocalHost(); read "....an InetAddress representing the loopback address is returned." so it appears that the implementation of getLocalHost() is incorrect on your UNIX and WIN boxes. The loopback address is nearly allways 127.0.0.1

    Found this comment "A host may have several IP addresses and other hosts may have to use different addresses to reach it. E.g. hosts on the intranet may have to use 192.168.0.100, but external machines may have to use 65.123.66.124. If you have a socket connection to another host you can call Socket.getLocalAddress() to find out which local address is used for the socket."

提交回复
热议问题