Skip to content

Commit b8bc7f8

Browse files
author
Rory Winston
committed
NET-261 NET-262: Clarify range assumptions and fix range checks
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/net/branches/NET_2_0@761983 13f79535-47bb-0310-9956-ffa450edef68
1 parent 6655daf commit b8bc7f8

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/main/java/org/apache/commons/net/util/SubnetUtils.java

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,13 @@ private SubnetInfo() {}
6969
private int low() { return network() + 1; }
7070
private int high() { return broadcast() - 1; }
7171

72+
/**
73+
* Returns true if the parameter <code>address</code> is in the
74+
* range of usable endpoint addresses for this subnet. This excludes the
75+
* network and broadcast adresses.
76+
* @param address A dot-delimited IPv4 address, e.g. "192.168.0.1"
77+
* @return True if in range, false otherwise
78+
*/
7279
public boolean isInRange(String address) { return isInRange(toInteger(address)); }
7380

7481
private boolean isInRange(int address) {
@@ -131,10 +138,12 @@ private void calculate(String mask) {
131138
address = matchAddress(matcher);
132139

133140
/* Create a binary netmask from the number of bits specification /x */
134-
int cidrPart = rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS-1);
141+
int cidrPart = rangeCheck(Integer.parseInt(matcher.group(5)), -1, NBITS-1);
135142
for (int j = 0; j < cidrPart; ++j) {
136143
netmask |= (1 << 31-j);
137144
}
145+
146+
rangeCheck(pop(netmask),0, NBITS);
138147

139148
/* Calculate base network address */
140149
network = (address & netmask);
@@ -165,7 +174,7 @@ private int toInteger(String address) {
165174
private int matchAddress(Matcher matcher) {
166175
int addr = 0;
167176
for (int i = 1; i <= 4; ++i) {
168-
int n = (rangeCheck(Integer.parseInt(matcher.group(i)), 0, 255));
177+
int n = (rangeCheck(Integer.parseInt(matcher.group(i)), -1, 255));
169178
addr |= ((n & 0xff) << 8*(4-i));
170179
}
171180
return addr;
@@ -196,10 +205,12 @@ private String format(int[] octets) {
196205
}
197206

198207
/*
199-
* Convenience function to check integer boundaries
208+
* Convenience function to check integer boundaries.
209+
* Checks if a value x is in the range (begin,end].
210+
* Returns x if it is in range, throws an exception otherwise.
200211
*/
201212
private int rangeCheck(int value, int begin, int end) {
202-
if (value > begin && value <= end) // (0,nbits]
213+
if (value > begin && value <= end) // (begin,end]
203214
return value;
204215

205216
throw new IllegalArgumentException("Value out of range: [" + value + "]");

0 commit comments

Comments
 (0)