关于如何在Java中检索多个IP地址(如果我有多个网卡)的一些疑问?
我在检索客户端的ip时遇到以下两个问题。
我在一个类中创建了以下代码:
private static InetAddress thisIp; static{ try { thisIp = InetAddress.getLocalHost(); System.out.println("MyIp is: " + thisIp); } catch(UnknownHostException ex) { } }
我的问题是:
1)前面的代码应检索客户端的IP地址,当我执行它时,它会打印以下消息:
MyIp是:andrea-virtual-machine / 127.0.1.1
为什么它以andrea-virtual-machine /开头? (我在虚拟机上开发),这是一个问题吗?
2)通过这种方式,我只能检索一个IP地址,但我可以拥有多个网卡,这样我就可以拥有多个IP地址但多个IP地址
我该怎么做才能处理这种情况? 我想把所有多个IP地址放入ArrayList
TNX
安德里亚
-
不,这不是问题,它只是一个由主机名和IP(
hostname/ip
)组成的输出。 您可能想要阅读的详细信息:实现类InetAddress
中的toString()
方法以返回此格式。 -
以下代码将列出系统中每个接口的所有IP地址(并将它们存储在您可以传递的列表中等等):
public static void main(String[] args) throws InterruptedException, IOException { List
allIps = new ArrayList (); Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = e.nextElement(); System.out.println(n.getName()); Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = ee.nextElement(); System.out.println(i.getHostAddress()); allIps.add(i.getHostAddress()); } } }
boolean isLoopbackAddress()
方法允许您过滤可能不需要的环回地址。
返回的InetAddress
是Inet4Address
或Inet6Address
,使用instanceof
可以确定返回的IP是IPv4还是IPv6格式。
顺便提一下,IP之前列出的主机名是INetAddress的一部分。 你得到了名字和地址,因为你没有试图只显示地址。
如果你的系统配置了多个ip,那么这样做。
try { InetAddress inet = InetAddress.getLocalHost(); InetAddress[] ips = InetAddress.getAllByName(inet.getCanonicalHostName()); if (ips != null ) { for (int i = 0; i < ips.length; i++) { System.out.println(ips[i]); } } } catch (UnknownHostException e) { }