您将需要使用NetworkInterface枚举网络接口。InetAddress.getLocalHost()总是返回环回。这并不能解释为什么得到127.0.1.1而不是127.0.0.1的原因,但是由于该方法没有执行您要尝试执行的操作,因此它似乎没有特别的意义。请参阅:http://docs.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html#getInetAddresses()
解决方法我的问题类似于这个问题。我想获取机器的真实IP(不是127.0.0.1),但是很奇怪,Ubuntu中的以下代码返回了127.0.1.1。
InetAddress.getLocalHost().getHostAddress()
以下是我的完整代码,最初在此处发布在SO中
public String getMachineIP() { try {String hostIP = InetAddress.getLocalHost().getHostAddress();if (!hostIP.equals('127.0.0.1')) { return hostIP;}/* * Above method often returns '127.0.0.1',In this case we need to * check all the available network interfaces */Enumeration<NetworkInterface> nInterfaces = NetworkInterface.getNetworkInterfaces();while (nInterfaces.hasMoreElements()) { Enumeration<InetAddress> inetAddresses = nInterfaces .nextElement().getInetAddresses(); while (inetAddresses.hasMoreElements()) {String address = inetAddresses.nextElement().getHostAddress();if (!address.equals('127.0.0.1')) { return address;} }} } catch (UnknownHostException e1) {System.err.println('Error = ' + e1.getMessage()); } catch (SocketException e1) {System.err.println('Error = ' + e1.getMessage()); } return null;}
上面的代码返回127.0.1.1,而ifconfig在我的Ubuntu机器上则给出以下输出
root@dell:~# ifconfigeth0 Link encap:Ethernet HWaddr 00:21:70:b7:30:cd UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) Interrupt:28 Base address:0x6000eth1 Link encap:Ethernet HWaddr 00:22:68:d3:02:b5 inet addr:192.168.2.112 Bcast:192.168.2.255 Mask:255.255.255.0 inet6 addr: fe80::222:68ff:fed3:2b5/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:23827 errors:0 dropped:0 overruns:0 frame:32515 TX packets:23200 errors:46 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:22027719 (22.0 MB) TX bytes:3778268 (3.7 MB) Interrupt:19loLink encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:402 errors:0 dropped:0 overruns:0 frame:0 TX packets:402 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:29197 (29.1 KB) TX bytes:29197 (29.1 KB)
我在主机文件中找到了127.0.1.1条目(对我来说很奇怪,因为我从未更新过此文件)
root@dell:~# cat /etc/hosts127.0.0.1 localhost127.0.1.1 dell# The following lines are desirable for IPv6 capable hosts::1 localhost ip6-localhost ip6-loopbackfe00::0 ip6-localnetff00::0 ip6-mcastprefixff02::1 ip6-allnodesff02::2 ip6-allroutersff02::3 ip6-allhosts
如何获取我的机器的真实IP(不是127.0.0.1)?我只在寻找IPv4地址,不包括127.0.0.0/8 subnet