Java 我是否可以仅筛选和选择InetAddress对象上的IPV4地址?如何排除IPV6?
我有以下问题:我创建了一个ArrayList,并将我的客户机的所有IP地址(如果客户机只有一张网卡,则为一个,如果客户机运行在一台有n张网卡的PC上,则为n个)放入该ArrayList,不包括环回地址、点对点地址和虚拟地址 我是这样做的:Java 我是否可以仅筛选和选择InetAddress对象上的IPV4地址?如何排除IPV6?,java,inetaddress,Java,Inetaddress,我有以下问题:我创建了一个ArrayList,并将我的客户机的所有IP地址(如果客户机只有一张网卡,则为一个,如果客户机运行在一台有n张网卡的PC上,则为n个)放入该ArrayList,不包括环回地址、点对点地址和虚拟地址 我是这样做的: private static List<String> allIps = new ArrayList<String>(); static { Enumeration<NetworkInterface> nets;
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());
}
使用调试器和控制台输出对我来说很清楚,在这种情况下,唯一存在的网络接口是eth0(这是正常的),但是,对于这个网络接口,我发现了2个IP地址(一个是IPV6地址,第二个是经典的IPV4地址)
因此,它把我的地址列表allIps都放进去了
我只想选择并放入我的allIps列表中的IPV4地址,而不是IPV6地址。我能做些什么呢?我是否可以在我的InetAddress对象上筛选并仅选择IPV4
Tnx
Andrea使用
实例和类型:
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
for (NetworkInterface ni :
Collections.list(NetworkInterface.getNetworkInterfaces())) {
for (InetAddress address : Collections.list(ni.getInetAddresses())) {
if (address instanceof Inet4Address) {
System.out.println(address);
}
}
}