所以,我试图获取我的机器的IP地址在我的本地网络(应为192.168.178.41)。
我的第一个意图是使用这样的东西:
InetAddress.getLocalHost().getHostAddress();
但它只返回127.0.0.1,这是正确的,但不是非常有用的我。
我搜索周围,发现这个答案http://stackoverflow.com/a/2381398/717341,它只是创建一个网页连接到某些网页(例如“google.com”),并从套接字获取本地主机地址:
Socket s = new Socket("google.com", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();
这对我的机器工作(它返回192.168.178.41),但它需要连接到互联网,以工作。由于我的应用程序不需要互联网连接,它可能看起来“可疑”的应用程序尝试连接到谷歌每次启动,我不喜欢使用它的想法。
所以,经过一些更多的研究,我偶然发现了NetworkInterface类,它(有一些工作)也返回所需的IP地址:
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()){
NetworkInterface current = interfaces.nextElement();
System.out.println(current);
if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
Enumeration addresses = current.getInetAddresses();
while (addresses.hasMoreElements()){
InetAddress current_addr = addresses.nextElement();
if (current_addr.isLoopbackAddress()) continue;
System.out.println(current_addr.getHostAddress());
}
}
在我的机器上,这会返回以下内容:
name:eth1 (eth1)
fe80:0:0:0:226:4aff:fe0d:592e%3
192.168.178.41
name:lo (lo)
它找到我的网络接口并返回所需的IP,但我不知道其他地址(fe80:0:0:0:226:4aff:fe0d:592e%3)的意思。
此外,我还没有找到一种方法从返回的地址过滤它(通过使用InetAddress对象的isXX()方法),然后使用RegEx,我发现非常“脏”。
任何其他的想法,使用RegEx或互联网?