Internet Person 2
Internet Person 2

Reputation: 21

Loop through IP addresses in range

What would the easiest and fastest way to loop through every ip address in a range (for example 104.200.16.0 to 104.200.31.255), preferably in java or js?

Upvotes: 1

Views: 1191

Answers (1)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16815

  1. Without any third party library:

Every IPv4 address can be converted to an integer, because essentially each part of an IP address is essentially a hex number from 00 to FF (in decimal from 0 to 255).

So we just have to convert the two addresses into integer and loop over the values between them:

// 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. Using a third party library:

Probably it would be easier to use a library like 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);
    }
}

Upvotes: 1

Related Questions