View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.net.util;
18  
19  import java.util.regex.Matcher;
20  import java.util.regex.Pattern;
21  
22  /**
23   * A class that performs some subnet calculations given a network address and a subnet mask.
24   * @see "http://www.faqs.org/rfcs/rfc1519.html"
25   * @since 2.0
26   */
27  public class SubnetUtils {
28  
29      private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})";
30      private static final String SLASH_FORMAT = IP_ADDRESS + "/(\\d{1,2})"; // 0 -> 32
31      private static final Pattern addressPattern = Pattern.compile(IP_ADDRESS);
32      private static final Pattern cidrPattern = Pattern.compile(SLASH_FORMAT);
33      private static final int NBITS = 32;
34  
35      private static final String PARSE_FAIL = "Could not parse [%s]";
36  
37      private final int netmask;
38      private final int address;
39      private final int network;
40      private final int broadcast;
41  
42      /** Whether the broadcast/network address are included in host count */
43      private boolean inclusiveHostCount;
44  
45  
46      /**
47       * Constructor that takes a CIDR-notation string, e.g. "192.168.0.1/16"
48       * @param cidrNotation A CIDR-notation string, e.g. "192.168.0.1/16"
49       * @throws IllegalArgumentException if the parameter is invalid,
50       * 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
51       */
52      public SubnetUtils(final String cidrNotation) {
53        final Matcher matcher = cidrPattern.matcher(cidrNotation);
54  
55        if (matcher.matches()) {
56            this.address = matchAddress(matcher);
57  
58            /* Create a binary netmask from the number of bits specification /x */
59  
60            final int trailingZeroes = NBITS - rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS);
61            /*
62             * An IPv4 netmask consists of 32 bits, a contiguous sequence
63             * of the specified number of ones followed by all zeros.
64             * So, it can be obtained by shifting an unsigned integer (32 bits) to the left by
65             * the number of trailing zeros which is (32 - the # bits specification).
66             * Note that there is no unsigned left shift operator, so we have to use
67             * a long to ensure that the left-most bit is shifted out correctly.
68             */
69            this.netmask = (int) (0x0FFFFFFFFL << trailingZeroes );
70  
71            /* Calculate base network address */
72            this.network = address & netmask;
73  
74            /* Calculate broadcast address */
75            this.broadcast = network | ~netmask;
76        } else {
77            throw new IllegalArgumentException(String.format(PARSE_FAIL, cidrNotation));
78        }
79      }
80  
81      /**
82       * Constructor that takes a dotted decimal address and a dotted decimal mask.
83       * @param address An IP address, e.g. "192.168.0.1"
84       * @param mask A dotted decimal netmask e.g. "255.255.0.0"
85       * @throws IllegalArgumentException if the address or mask is invalid,
86       * i.e. does not match n.n.n.n where n=1-3 decimal digits and the mask is not all zeros
87       */
88      public SubnetUtils(final String address, final String mask) {
89          this.address = toInteger(address);
90          this.netmask = toInteger(mask);
91  
92          if ((this.netmask & -this.netmask) - 1 != ~this.netmask) {
93              throw new IllegalArgumentException(String.format(PARSE_FAIL, mask));
94          }
95  
96          /* Calculate base network address */
97          this.network = this.address & this.netmask;
98  
99          /* 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 }