J
J
javedimka2019-02-10 06:31:37
Computer networks
javedimka, 2019-02-10 06:31:37

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

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

The code is clear, almost all, in all the examples I found there are pieces of code:
double x = Math.log( end - start + 1) / Math.log( 2 );
byte maxDiff = (byte)( 32 - Math.floor( x ) );
if ( maxSize < maxDiff) {
        maxSize = maxDiff;
}

But nowhere is there an explanation of what kind of mathematics is going on here and how natural logarithms are related to this whole topic.
Can you please explain what is going on here?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question