IP Address not obtained in java

前端 未结 5 1107
北海茫月
北海茫月 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:00

    When you use InetAddress.getLocalHost() you are not guaranteed to get a particular interface, ie. you could receive the loopback (127) interface or a connected one.

    In order to ensure you always get an external interface, you should use the java.net.NetworkInterface class. The static getByName(String) class will give you the interface with the defined name (such as "eth0"). Then you can use the getInetAddresses() function to obtain the IP addresses (could be just one) bound to that interface.

    NetworkInterface ni = NetworkInterface.getByName("eth1");
    ni.getInetAddresses();
    

提交回复
热议问题