Today I used commons-net to verify when an IP address is in a subnet specified in CIDR notation. So, I got a bug.

This code:

SubnetUtils utils = new SubnetUtils("77.24.0.0/16");
System.out.println("lower address: " + utils.getInfo().getLowAddress());
System.out.println("higher address: " + utils.getInfo().getHighAddress());
System.out.println("77.23.255.254 is in range? :" + utils.getInfo().isInRange( "77.23.255.254" ));

gives this output:

lower address: 77.24.0.1
higher address: 77.24.255.254
77.23.255.254 is in range? :true

Obviously the last ip is not in range...

From the sources you see how the isInRange is implemented:

private boolean isInRange(int address)      { return ((address-low()) <= (high()-low())); }

Wrong.

So I fixed in my caller code with a my implementation of isInRange:

private boolean isInRange( SubnetInfo info, String remoteAddr ) {
    int address = info.asInteger( remoteAddr );
    int low = info.asInteger( info.getLowAddress() );
    int high = info.asInteger( info.getHighAddress() );
    return low <= address && address <= high;
}

Unfortunately low and high are not accessible, so I had to convert to int from the string representation.


3 Responses to “Checking if an IP is in a subnet range. SubnetUtils.SubnetInfo isInRange bug.”  

  1. 1 Urko

    Hi Luigi,

    I’ve the same problem with Apache Commons. I’ve downloaded the latest version, and still fails.

    I’ve make some “changes” to your code. I’ve changed the “isInRange(String)” method, and not to add new method -like you-

    // Doesn’t go OK
    // public boolean isInRange(String address) { return isInRange(toInteger(address)); }
    private boolean isInRange(int address) { return ((address-low())

  2. 2 apricoti

    Looks like this is fixed in commons-net version 3.1

    They have the following code now:

    118 private boolean isInRange(int address) {
    119 int diff = address-low();
    120 return (diff >= 0 && (diff <= (high()-low())));
    121 }

    Which is equivalent to what is suggested above:

    return low() <= address && address <= high();

    I don't know why they have the extra "diff" and "high()-low()" calculations when the other way is clearer.

  3. 3 adilbk

    I’ve the same problem. just use last version 3.3. its working for me.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



Calendar

March 2009
M T W T F S S
« Feb   Apr »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Follow me

twitter flickr LinkedIn feed

Subscribe by email

Enter your email address:

Archives


Categories

Tag Cloud


Listening