我有以下问题:我创建了一个 ArrayList 并将我的客户端的所有 IP 地址放入此数组列表中(如果客户端有一个网卡,则为一个,如果客户端在具有 n 个网卡的 PC 上运行,则为 n)不包括环回地址、点对点地址和虚拟地址。
我已经这样做了:
private static List<String> allIps = new ArrayList<String>();
static {
Enumeration<NetworkInterface> nets;
try {
nets = NetworkInterface.getNetworkInterfaces();
while(nets.hasMoreElements()) {
NetworkInterface current = nets.nextElement();
if ((current.isUp()) && (!current.isPointToPoint()) && (!current.isVirtual()) && (!current.isLoopback())) {
System.out.println(current.getName());
Enumeration<InetAddress> ee = current.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress i = ee.nextElement();
System.out.println(i.getHostAddress());
allIps.add(i.getHostAddress());
}
}
}
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("List of all IP on this client: "
+ allIps.toString());
System.out.println("Number of ip: " + allIps.size());
}
看起来效果很好,唯一的问题是我的输出(在 Eclipse 控制台中)是:
eth0
fe80:0:0:0:20c:29ff:fe15:3dfe%2
192.168.15.135
List of all IP on this client: [fe80:0:0:0:20c:29ff:fe15:3dfe%2, 192.168.15.135]
Number of ip: 2
使用调试器和控制台输出对我来说很清楚,在这种情况下,唯一存在的网络接口是eth0(这没关系)但是,对于这个网络接口,id 找到了 2 个 IP 地址(适合的一个是 IPV6 地址,第二个是经典的IPV4地址)
所以它把所有的地址都放在了我的地址列表中。
我只想选择并放入我的allIps列表中的IPV4地址,而不是 IPV6。我能做些什么呢?我可以在InetAddress对象上过滤并仅选择 IPV4 吗?
肿瘤坏死因子
安德烈亚