I am trying to fetch all IP lists with in CIDR range using JAVA. I got one sample code, but I am not sure it’s working fine for all scenarios or not. Using java.net package.
public static List<String> getIPsInCIDR(String cidrRange) {
List<String> ips = new ArrayList<>();
try {
// Split the CIDR range into IP and prefix length
String[] parts = cidrRange.split("/");
String ip = parts[0];
int prefix = Integer.parseInt(parts[1]);
// Calculate the number of addresses in the range
int numAddresses = (int) Math.pow(2, (32 - prefix));
// Convert the IP address to a byte array
byte[] ipBytes = InetAddress.getByName(ip).getAddress();
// Convert the byte array to an integer
int ipAddress = 0;
for (byte b : ipBytes) {
ipAddress = (ipAddress << 8) | (b & 0xFF);
}
// Generate the list of IP addresses within the range
for (int i = 0; i < numAddresses; i++) {
int currentIP = ipAddress + i;
// Convert the integer back to a byte array
byte[] currentIPBytes = new byte[4];
for (int j = 3; j >= 0; j--) {
currentIPBytes[j] = (byte) (currentIP & 0xFF);
currentIP >>= 8;
}
// Create InetAddress object from the byte array
InetAddress address = InetAddress.getByAddress(currentIPBytes);
// Add IP address to the list
ips.add(address.getHostAddress());
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ips;
}
Could you please check this and confirm. I tried this is works fine