Fix a bug in CIDR.contains(InetAddress) implementations

Related issue: #2767

Motivation:

CIDR.contains(InetAddress) implementations should always return true
when the CIDR's prefix length is 0.

Modifications:

- Make CIDR.contains(InetAddress) return true if the current cidrMask is
  0
- Add tests

Result:

Fixed the issue #2767
This commit is contained in:
Trustin Lee 2014-08-26 16:29:54 +09:00
parent 907d38e9fe
commit 534840a696
3 changed files with 25 additions and 1 deletions

View File

@ -89,6 +89,14 @@ public class CIDR4 extends CIDR {
@Override
public boolean contains(InetAddress inetAddress) {
if (inetAddress == null) {
throw new NullPointerException("inetAddress");
}
if (cidrMask == 0) {
return true;
}
int search = ipv4AddressToInt(inetAddress);
return search >= addressInt && search <= addressEndInt;
}

View File

@ -93,6 +93,14 @@ public class CIDR6 extends CIDR {
@Override
public boolean contains(InetAddress inetAddress) {
if (inetAddress == null) {
throw new NullPointerException("inetAddress");
}
if (cidrMask == 0) {
return true;
}
BigInteger search = ipv6AddressToBigInteger(inetAddress);
return search.compareTo(addressBigInt) >= 0 && search.compareTo(addressEndBigInt) <= 0;
}

View File

@ -246,6 +246,15 @@ public class IpFilterRuleTest {
addr = new InetSocketAddress(InetAddress.getByName(InetAddress.getLocalHost().getHostName()), 8080);
assertTrue(accept(h, addr));
h.clear();
h.addAll(new IpFilterRuleList("+c:0.0.0.0/0, -n:*"));
addr = new InetSocketAddress("91.114.240.43", 8080);
assertTrue(accept(h, addr));
addr = new InetSocketAddress("10.0.0.3", 8080);
assertTrue(accept(h, addr));
addr = new InetSocketAddress("192.168.93.2", 8080);
assertTrue(accept(h, addr));
h.clear();
h.addAll(new IpFilterRuleList(""));
addr = new InetSocketAddress(InetAddress.getLocalHost(), 8080);
@ -262,7 +271,6 @@ public class IpFilterRuleTest {
assertTrue(accept(h, addr));
addr = new InetSocketAddress(InetAddress.getByName(InetAddress.getLocalHost().getHostName()), 8080);
assertTrue(accept(h, addr));
}
}