【问题标题】:Loop through IP addresses in range循环访问范围内的 IP 地址
【发布时间】:2021-11-23 18:43:15
【问题描述】:

在一个范围内(例如 104.200.16.0 到 104.200.31.255)循环遍历每个 IP 地址的最简单和最快的方法是什么,最好是在 java 或 js 中?

【问题讨论】:

标签: java ip


【解决方案1】:
  1. 没有任何第三方库:

每个 IPv4 地址都可以转换为整数,因为基本上 IP 地址的每个部分本质上都是从 00FF 的十六进制数字(从 0255 的十进制数)。

所以我们只需要将两个地址转换为整数并遍历它们之间的值:

// Convert a string representing an IP to an integer
private static int convertToInt(String address) throws UnknownHostException {
    InetAddress inetAddress = Inet4Address.getByName(address);
    return ByteBuffer.allocate(4).put(inetAddress.getAddress()).getInt(0);
}

// Convert an integer to an IP string
private static String convertToIp(int address) throws UnknownHostException {
    return Inet4Address.getByAddress(ByteBuffer.allocate(4).putInt(address).array()).getHostAddress();
}

public static void generate(String address1, String address2) throws UnknownHostException {
    int numeric1 = convertToInt(address1);
    int numeric2 = convertToInt(address2);
    for (int i = Math.min(numeric1, numeric2); i <= Math.max(numeric1, numeric2); i++) {
        System.out.println(convertToIp(i));
    }
}
  1. 使用第三方库:

使用IPAddress 之类的库可能会更容易。

public static void generate(String lowerAddress, String upperAddress) throws AddressStringException {
    IPAddress lower = new IPAddressString(lowerAddress).toAddress();
    IPAddress upper = new IPAddressString(upperAddress).toAddress();
    IPAddressSeqRange range = lower.toSequentialRange(upper);
    for(IPAddress address : range.getIterable()) {
        System.out.println(address);
    }
}

【讨论】:

    猜你喜欢
    • 2013-08-22
    • 2022-07-22
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2023-03-28
    • 2010-12-03
    • 2020-10-07
    • 2017-11-27
    相关资源
    最近更新 更多