简体   繁体   English

我如何只获得 IPv4 地址

[英]How would I get only IPv4 addresses

I have the following code which is supposed to get only the IPv4 addresses of all active interfaces, but it still returns an IPv6 address on some computers.我有以下代码,它应该只获取所有活动接口的 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;
}

I've tried to specify using only IPv4 by using System.setProperty("java.net.preferIPv4Stack" , "true");我试图通过使用System.setProperty("java.net.preferIPv4Stack" , "true");来指定仅使用 IPv4 System.setProperty("java.net.preferIPv4Stack" , "true"); , but this only causes getIpAddress() to return an empty list. ,但这只会导致getIpAddress()返回一个空列表。 How should I be getting the IPv4 of active interfaces without the use of string manipulation?我应该如何在不使用字符串操作的情况下获取活动接口的 IPv4?

EDIT:编辑:

Using System.setProperty("java.net.preferIPv4Stack" , "true");使用System.setProperty("java.net.preferIPv4Stack" , "true"); always causes getIpAddress() to return an empty list.总是导致getIpAddress()返回一个空列表。

From 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.简而言之,当地址是 IPv4 地址时,它是一个 IP 地址、一个子网掩码和一个广播地址。 An IP address and a network prefix length in the case of IPv6 address. IPv6 地址的 IP 地址和网络前缀长度。

Here's my code:这是我的代码:

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));
    }
  }
}

My Kotlin solution:我的 Kotlin 解决方案:

  private suspend fun getAllActiveInterfaces(): Sequence<NetworkInterface> {
        return withContext(Dispatchers.IO) {
            NetworkInterface
                .getNetworkInterfaces()
                .asSequence()
                .filter { !it.isLoopback && it.isUp && !blackListedInterfaces.contains(it.name) }
        }
    }
    suspend fun getAllAddresses(): Result<Collection<InetAddress>> {
        return withContextCatching(Dispatchers.IO) {
            getAllActiveInterfaces()
                .map { networkInterface ->
                    networkInterface
                        .also { Timber.d("Interface: ${it.name}") }
                        .interfaceAddresses
                        .mapNotNull { it.address }
                        .filterIsInstance<Inet4Address>()
                }
                .flatten()
                .toSet()
        }
    }
private val blackListedInterfaces = setOf("dummy0")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM