001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.net.util; 018 019import java.util.regex.Matcher; 020import java.util.regex.Pattern; 021 022/** 023 * A class that performs some subnet calculations given a network address and a subnet mask. 024 * @see "http://www.faqs.org/rfcs/rfc1519.html" 025 * @since 2.0 026 */ 027public class SubnetUtils { 028 029 private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})"; 030 private static final String SLASH_FORMAT = IP_ADDRESS + "/(\\d{1,2})"; // 0 -> 32 031 private static final Pattern addressPattern = Pattern.compile(IP_ADDRESS); 032 private static final Pattern cidrPattern = Pattern.compile(SLASH_FORMAT); 033 private static final int NBITS = 32; 034 035 private static final String PARSE_FAIL = "Could not parse [%s]"; 036 037 private final int netmask; 038 private final int address; 039 private final int network; 040 private final int broadcast; 041 042 /** Whether the broadcast/network address are included in host count */ 043 private boolean inclusiveHostCount; 044 045 046 /** 047 * Constructor that takes a CIDR-notation string, e.g. "192.168.0.1/16" 048 * @param cidrNotation A CIDR-notation string, e.g. "192.168.0.1/16" 049 * @throws IllegalArgumentException if the parameter is invalid, 050 * i.e. does not match n.n.n.n/m where n=1-3 decimal digits, m = 1-2 decimal digits in range 0-32 051 */ 052 public SubnetUtils(final String cidrNotation) { 053 final Matcher matcher = cidrPattern.matcher(cidrNotation); 054 055 if (matcher.matches()) { 056 this.address = matchAddress(matcher); 057 058 /* Create a binary netmask from the number of bits specification /x */ 059 060 final int trailingZeroes = NBITS - rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS); 061 /* 062 * An IPv4 netmask consists of 32 bits, a contiguous sequence 063 * of the specified number of ones followed by all zeros. 064 * So, it can be obtained by shifting an unsigned integer (32 bits) to the left by 065 * the number of trailing zeros which is (32 - the # bits specification). 066 * Note that there is no unsigned left shift operator, so we have to use 067 * a long to ensure that the left-most bit is shifted out correctly. 068 */ 069 this.netmask = (int) (0x0FFFFFFFFL << trailingZeroes ); 070 071 /* Calculate base network address */ 072 this.network = address & netmask; 073 074 /* Calculate broadcast address */ 075 this.broadcast = network | ~netmask; 076 } else { 077 throw new IllegalArgumentException(String.format(PARSE_FAIL, cidrNotation)); 078 } 079 } 080 081 /** 082 * Constructor that takes a dotted decimal address and a dotted decimal mask. 083 * @param address An IP address, e.g. "192.168.0.1" 084 * @param mask A dotted decimal netmask e.g. "255.255.0.0" 085 * @throws IllegalArgumentException if the address or mask is invalid, 086 * i.e. does not match n.n.n.n where n=1-3 decimal digits and the mask is not all zeros 087 */ 088 public SubnetUtils(final String address, final String mask) { 089 this.address = toInteger(address); 090 this.netmask = toInteger(mask); 091 092 if ((this.netmask & -this.netmask) - 1 != ~this.netmask) { 093 throw new IllegalArgumentException(String.format(PARSE_FAIL, mask)); 094 } 095 096 /* Calculate base network address */ 097 this.network = this.address & this.netmask; 098 099 /* Calculate broadcast address */ 100 this.broadcast = this.network | ~this.netmask; 101 } 102 103 104 /** 105 * Returns <code>true</code> if the return value of {@link SubnetInfo#getAddressCount()} 106 * includes the network and broadcast addresses. 107 * @since 2.2 108 * @return true if the host count includes the network and broadcast addresses 109 */ 110 public boolean isInclusiveHostCount() { 111 return inclusiveHostCount; 112 } 113 114 /** 115 * Set to <code>true</code> if you want the return value of {@link SubnetInfo#getAddressCount()} 116 * to include the network and broadcast addresses. 117 * This also applies to {@link SubnetInfo#isInRange(int)} 118 * @param inclusiveHostCount true if network and broadcast addresses are to be included 119 * @since 2.2 120 */ 121 public void setInclusiveHostCount(final boolean inclusiveHostCount) { 122 this.inclusiveHostCount = inclusiveHostCount; 123 } 124 125 126 127 /** 128 * Convenience container for subnet summary information. 129 * 130 */ 131 public final class SubnetInfo { 132 /* Mask to convert unsigned int to a long (i.e. keep 32 bits) */ 133 private static final long UNSIGNED_INT_MASK = 0x0FFFFFFFFL; 134 135 private SubnetInfo() {} 136 137 // long versions of the values (as unsigned int) which are more suitable for range checking 138 private long networkLong() { return network & UNSIGNED_INT_MASK; } 139 private long broadcastLong(){ return broadcast & UNSIGNED_INT_MASK; } 140 141 private int low() { 142 return isInclusiveHostCount() ? network : 143 broadcastLong() - networkLong() > 1 ? network + 1 : 0; 144 } 145 146 private int high() { 147 return isInclusiveHostCount() ? broadcast : 148 broadcastLong() - networkLong() > 1 ? broadcast -1 : 0; 149 } 150 151 /** 152 * Returns true if the parameter <code>address</code> is in the 153 * range of usable endpoint addresses for this subnet. This excludes the 154 * network and broadcast addresses. Use {@link SubnetUtils#setInclusiveHostCount(boolean)} 155 * to change this. 156 * @param address A dot-delimited IPv4 address, e.g. "192.168.0.1" 157 * @return True if in range, false otherwise 158 */ 159 public boolean isInRange(final String address) { 160 return isInRange(toInteger(address)); 161 } 162 163 /** 164 * Returns true if the parameter <code>address</code> is in the 165 * range of usable endpoint addresses for this subnet. This excludes the 166 * network and broadcast addresses by default. Use {@link SubnetUtils#setInclusiveHostCount(boolean)} 167 * to change this. 168 * @param address the address to check 169 * @return true if it is in range 170 * @since 3.4 (made public) 171 */ 172 public boolean isInRange(final int address) { 173 if (address == 0) { // cannot ever be in range; rejecting now avoids problems with CIDR/31,32 174 return false; 175 } 176 final long addLong = address & UNSIGNED_INT_MASK; 177 final long lowLong = low() & UNSIGNED_INT_MASK; 178 final long highLong = high() & UNSIGNED_INT_MASK; 179 return addLong >= lowLong && addLong <= highLong; 180 } 181 182 public String getBroadcastAddress() { 183 return format(toArray(broadcast)); 184 } 185 186 public String getNetworkAddress() { 187 return format(toArray(network)); 188 } 189 190 public String getNetmask() { 191 return format(toArray(netmask)); 192 } 193 194 public String getAddress() { 195 return format(toArray(address)); 196 } 197 198 public String getNextAddress() { 199 return format(toArray(address + 1)); 200 } 201 202 public String getPreviousAddress() { 203 return format(toArray(address - 1)); 204 } 205 206 /** 207 * Return the low address as a dotted IP address. 208 * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. 209 * 210 * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address 211 */ 212 public String getLowAddress() { 213 return format(toArray(low())); 214 } 215 216 /** 217 * Return the high address as a dotted IP address. 218 * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. 219 * 220 * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address 221 */ 222 public String getHighAddress() { 223 return format(toArray(high())); 224 } 225 226 /** 227 * Get the count of available addresses. 228 * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. 229 * @return the count of addresses, may be zero. 230 * @throws RuntimeException if the correct count is greater than {@code Integer.MAX_VALUE} 231 * @deprecated (3.4) use {@link #getAddressCountLong()} instead 232 */ 233 @Deprecated 234 public int getAddressCount() { 235 final long countLong = getAddressCountLong(); 236 if (countLong > Integer.MAX_VALUE) { 237 throw new RuntimeException("Count is larger than an integer: " + countLong); 238 } 239 // N.B. cannot be negative 240 return (int)countLong; 241 } 242 243 /** 244 * Get the count of available addresses. 245 * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. 246 * @return the count of addresses, may be zero. 247 * @since 3.4 248 */ 249 public long getAddressCountLong() { 250 final long b = broadcastLong(); 251 final long n = networkLong(); 252 final long count = b - n + (isInclusiveHostCount() ? 1 : -1); 253 return count < 0 ? 0 : count; 254 } 255 256 public int asInteger(final String address) { 257 return toInteger(address); 258 } 259 260 public String getCidrSignature() { 261 return format(toArray(address)) + "/" + pop(netmask); 262 } 263 264 public String[] getAllAddresses() { 265 final int ct = getAddressCount(); 266 final String[] addresses = new String[ct]; 267 if (ct == 0) { 268 return addresses; 269 } 270 for (int add = low(), j=0; add <= high(); ++add, ++j) { 271 addresses[j] = format(toArray(add)); 272 } 273 return addresses; 274 } 275 276 /* 277 * Convert a packed integer address into a 4-element array 278 */ 279 private int[] toArray(final int val) { 280 final int ret[] = new int[4]; 281 for (int j = 3; j >= 0; --j) { 282 ret[j] |= val >>> 8*(3-j) & 0xff; 283 } 284 return ret; 285 } 286 287 /* 288 * Convert a 4-element array into dotted decimal format 289 */ 290 private String format(final int[] octets) { 291 final StringBuilder str = new StringBuilder(); 292 for (int i =0; i < octets.length; ++i){ 293 str.append(octets[i]); 294 if (i != octets.length - 1) { 295 str.append("."); 296 } 297 } 298 return str.toString(); 299 } 300 301 /** 302 * {@inheritDoc} 303 * @since 2.2 304 */ 305 @Override 306 public String toString() { 307 final StringBuilder buf = new StringBuilder(); 308 buf.append("CIDR Signature:\t[").append(getCidrSignature()).append("]") 309 .append(" Netmask: [").append(getNetmask()).append("]\n") 310 .append("Network:\t[").append(getNetworkAddress()).append("]\n") 311 .append("Broadcast:\t[").append(getBroadcastAddress()).append("]\n") 312 .append("First Address:\t[").append(getLowAddress()).append("]\n") 313 .append("Last Address:\t[").append(getHighAddress()).append("]\n") 314 .append("# Addresses:\t[").append(getAddressCount()).append("]\n"); 315 return buf.toString(); 316 } 317 } 318 319 /** 320 * Return a {@link SubnetInfo} instance that contains subnet-specific statistics 321 * @return new instance 322 */ 323 public final SubnetInfo getInfo() { return new SubnetInfo(); } 324 325 /* 326 * Convert a dotted decimal format address to a packed integer format 327 */ 328 private static int toInteger(final String address) { 329 final Matcher matcher = addressPattern.matcher(address); 330 if (matcher.matches()) { 331 return matchAddress(matcher); 332 } 333 throw new IllegalArgumentException(String.format(PARSE_FAIL, address)); 334 } 335 336 /* 337 * Convenience method to extract the components of a dotted decimal address and 338 * pack into an integer using a regex match 339 */ 340 private static int matchAddress(final Matcher matcher) { 341 int addr = 0; 342 for (int i = 1; i <= 4; ++i) { 343 final int n = rangeCheck(Integer.parseInt(matcher.group(i)), 0, 255); 344 addr |= (n & 0xff) << 8*(4-i); 345 } 346 return addr; 347 } 348 349 /* 350 * Convenience function to check integer boundaries. 351 * Checks if a value x is in the range [begin,end]. 352 * Returns x if it is in range, throws an exception otherwise. 353 */ 354 private static int rangeCheck(final int value, final int begin, final int end) { 355 if (value >= begin && value <= end) { // (begin,end] 356 return value; 357 } 358 359 throw new IllegalArgumentException("Value [" + value + "] not in range ["+begin+","+end+"]"); 360 } 361 362 /* 363 * Count the number of 1-bits in a 32-bit integer using a divide-and-conquer strategy 364 * see Hacker's Delight section 5.1 365 */ 366 int pop(int x) { 367 x = x - (x >>> 1 & 0x55555555); 368 x = (x & 0x33333333) + (x >>> 2 & 0x33333333); 369 x = x + (x >>> 4) & 0x0F0F0F0F; 370 x = x + (x >>> 8); 371 x = x + (x >>> 16); 372 return x & 0x0000003F; 373 } 374 375 public SubnetUtils getNext() { 376 return new SubnetUtils(getInfo().getNextAddress(), getInfo().getNetmask()); 377 } 378 379 public SubnetUtils getPrevious() { 380 return new SubnetUtils(getInfo().getPreviousAddress(), getInfo().getNetmask()); 381 } 382 383}