Answer the question
In order to leave comments, you need to log in
Convert IP address range to CIDR?
There are many code examples on the Internet that allow you to make the necessary transformations, for example, there are examples on the link for 5 different languages, I will give an example in Java here
public static List<String> iprange2cidr( int ipStart, int ipEnd ) {
long start = ipStart;
long end = ipEnd;
ArrayList<String> result = new ArrayList<String>();
while ( end >= start ) {
byte maxSize = 32;
while ( maxSize > 0) {
long mask = iMask( maxSize - 1 );
long maskBase = start & mask;
if ( maskBase != start ) {
break;
}
maxSize--;
}
double x = Math.log( end - start + 1) / Math.log( 2 );
byte maxDiff = (byte)( 32 - Math.floor( x ) );
if ( maxSize < maxDiff) {
maxSize = maxDiff;
}
String ip = long2ip(start);
result.add( ip + "/" + maxSize);
start += Math.pow( 2, (32 - maxSize) );
}
return result;
}
private static long iMask(int s) {
return Math.round(Math.pow(2, 32) - Math.pow(2, (32 - s)));
}
private static long ip2long(String ipstring) {
String[] ipAddressInArray = ipstring.split("\\.");
long num = 0;
long ip = 0;
for (int x = 3; x >= 0; x--) {
ip = Long.parseLong(ipAddressInArray[3 - x]);
num |= ip << (x << 3);
}
return num;
}
private static String long2ip(long longIP) {
StringBuffer sbIP = new StringBuffer("");
sbIP.append(String.valueOf(longIP >>> 24));
sbIP.append(".");
sbIP.append(String.valueOf((longIP & 0x00FFFFFF) >>> 16));
sbIP.append(".");
sbIP.append(String.valueOf((longIP & 0x0000FFFF) >>> 8));
sbIP.append(".");
sbIP.append(String.valueOf(longIP & 0x000000FF));
return sbIP.toString();
}
double x = Math.log( end - start + 1) / Math.log( 2 );
byte maxDiff = (byte)( 32 - Math.floor( x ) );
if ( maxSize < maxDiff) {
maxSize = maxDiff;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question