gpt4 book ai didi

java - 我怎样才能只获得 IPv4 地址

转载 作者:行者123 更新时间:2023-11-30 10:34:23 25 4
gpt4 key购买 nike

我有以下代码,它应该只获取所有 Activity 接口(interface)的 IPv4 地址,但它仍然在某些计算机上返回 IPv6 地址。

public static List<List> getIpAddress() {
List<String> ip = new ArrayList<>();
List<List> ipRefined = new ArrayList<>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
ip.add(addresses.nextElement().getHostAddress());
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
for(int x = 0; x < ip.size(); x++){
if(ip.get(x).contains("%")){
try {
if (ip.get(x + 1).contains(".")) {
List<String> tempList = new ArrayList<>();
tempList.add(ip.get(x).substring(ip.get(x).indexOf("%") + 1));
tempList.add(ip.get(x + 1));
ipRefined.add(tempList);
}
} catch (IndexOutOfBoundsException ae) {
}
}
}
return ipRefined;
}

我尝试使用 System.setProperty("java.net.preferIPv4Stack", "true"); 指定仅使用 IPv4,但这只会导致 getIpAddress() 返回一个空列表。我应该如何在不使用字符串操作的情况下获取 Activity 接口(interface)的 IPv4?

编辑:

使用 System.setProperty("java.net.preferIPv4Stack", "true"); 总是导致 getIpAddress() 返回空列表。

最佳答案

来自 InterfaceAddress

This class represents a Network Interface address. In short it's an IP address, a subnet mask and a broadcast address when the address is an IPv4 one. An IP address and a network prefix length in the case of IPv6 address.

这是我的代码:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
System.out.println(String.format("networkInterface: %s", networkInterface.toString()));

if (!networkInterface.isUp()) {
continue;
}

for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
int npf = interfaceAddress.getNetworkPrefixLength();
InetAddress address = interfaceAddress.getAddress();
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null && npf != 8) {
System.out.println(String.format("IPv6: %s; Network Prefix Length: %s", address, npf));
} else {
System.out.println(String.format("IPv4: %s; Subnet Mask: %s; Broadcast: %s", address, npf, broadcast));
}
}
}

关于java - 我怎样才能只获得 IPv4 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com