    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     */
    017    package org.apache.commons.net.util;
    018
    019    import java.util.regex.Matcher;
    020    import 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     * @author <rwinston@apache.org>
    026     * @since 2.0
    027     */
    028    public class SubnetUtils {
    029
    030        private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})";
    031        private static final String SLASH_FORMAT = IP_ADDRESS + "/(\\d{1,3})";
    032        private static final Pattern addressPattern = Pattern.compile(IP_ADDRESS);
    033        private static final Pattern cidrPattern = Pattern.compile(SLASH_FORMAT);
    034        private static final int NBITS = 32;
    035
    036        private int netmask = 0;
    037        private int address = 0;
    038        private int network = 0;
    039        private int broadcast = 0;
    040
    041        /** Whether the broadcast/network address are included in host count */
    042        private boolean inclusiveHostCount = false;
    043
    044
    045        /**
    046         * Constructor that takes a CIDR-notation string, e.g. "192.168.0.1/16"
    047         * @param cidrNotation A CIDR-notation string, e.g. "192.168.0.1/16"
    048         * @throws IllegalArgumentException if the parameter is invalid,
    049         * i.e. does not match n.n.n.n/m where n=1-3 decimal digits, m = 1-3 decimal digits in range 1-32
    050         */
    051        public SubnetUtils(String cidrNotation) {
    052            calculate(cidrNotation);
    053        }
    054
    055        /**
    056         * Constructor that takes a dotted decimal address and a dotted decimal mask.
    057         * @param address An IP address, e.g. "192.168.0.1"
    058         * @param mask A dotted decimal netmask e.g. "255.255.0.0"
    059         * @throws IllegalArgumentException if the address or mask is invalid,
    060         * i.e. does not match n.n.n.n where n=1-3 decimal digits and the mask is not all zeros
    061         */
    062        public SubnetUtils(String address, String mask) {
    063            calculate(toCidrNotation(address, mask));
    064        }
    065
    066
    067        /**
    068         * Returns <code>true</code> if the return value of {@link SubnetInfo#getAddressCount()}
    069         * includes the network address and broadcast addresses.
    070         * @since 2.2
    071         */
    072        public boolean isInclusiveHostCount() {
    073            return inclusiveHostCount;
    074        }
    075
    076        /**
    077         * Set to <code>true</code> if you want the return value of {@link SubnetInfo#getAddressCount()}
    078         * to include the network and broadcast addresses.
    079         * @param inclusiveHostCount
    080         * @since 2.2
    081         */
    082        public void setInclusiveHostCount(boolean inclusiveHostCount) {
    083            this.inclusiveHostCount = inclusiveHostCount;
    084        }
    085
    086
    087
    088        /**
    089         * Convenience container for subnet summary information.
    090         *
    091         */
    092        public final class SubnetInfo {
    093            private SubnetInfo() {}
    094
    095            private int netmask()       { return netmask; }
    096            private int network()       { return network; }
    097            private int address()       { return address; }
    098            private int broadcast()     { return broadcast; }
    099
    100            private int low() {
    101                return (isInclusiveHostCount() ? network() :
    102                    broadcast() - network() > 1 ? network() + 1 : 0);
    103            }
    104            private int high() {
    105                return (isInclusiveHostCount() ? broadcast() :
    106                    broadcast() - network() > 1 ? broadcast() -1  : 0);
    107            }
    108
    109            /**
    110             * Returns true if the parameter <code>address</code> is in the
    111             * range of usable endpoint addresses for this subnet. This excludes the
    112             * network and broadcast adresses.
    113             * @param address A dot-delimited IPv4 address, e.g. "192.168.0.1"
    114             * @return True if in range, false otherwise
    115             */
    116            public boolean isInRange(String address)    { return isInRange(toInteger(address)); }
    117
    118            private boolean isInRange(int address)      {
    119                int diff = address-low();
    120                return (diff >= 0 && (diff <= (high()-low())));
    121            }
    122
    123            public String getBroadcastAddress()         { return format(toArray(broadcast())); }
    124            public String getNetworkAddress()           { return format(toArray(network())); }
    125            public String getNetmask()                  { return format(toArray(netmask())); }
    126            public String getAddress()                  { return format(toArray(address())); }
    127
    128            /**
    129             * Return the low address as a dotted IP address.
    130             * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false.
    131             *
    132             * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address
    133             */
    134            public String getLowAddress()               { return format(toArray(low())); }
    135
    136            /**
    137             * Return the high address as a dotted IP address.
    138             * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false.
    139             *
    140             * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address
    141             */
    142            public String getHighAddress()              { return format(toArray(high())); }
    143
    144            /**
    145             * Get the count of available addresses.
    146             * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false.
    147             * @return the count of addresses, may be zero.
    148             */
    149            public int getAddressCount()                {
    150                int count = broadcast() - network() + (isInclusiveHostCount() ? 1 : -1);
    151                return count < 0 ? 0 : count;
    152            }
    153
    154            public int asInteger(String address)        { return toInteger(address); }
    155
    156            public String getCidrSignature() {
    157                return toCidrNotation(
    158                        format(toArray(address())),
    159                        format(toArray(netmask()))
    160                );
    161            }
    162
    163            public String[] getAllAddresses() {
    164                String[] addresses = new String[getAddressCount()];
    165                for (int add = low(), j=0; add <= high(); ++add, ++j) {
    166                    addresses[j] = format(toArray(add));
    167                }
    168                return addresses;
    169            }
    170
    171            /**
    172             * {@inheritDoc}
    173             * @since 2.2
    174             */
    175            @Override
    176            public String toString() {
    177                final StringBuilder buf = new StringBuilder();
    178                buf.append("CIDR Signature:\t[").append(getCidrSignature()).append("]")
    179                    .append(" Netmask: [").append(getNetmask()).append("]\n")
    180                    .append("Network:\t[").append(getNetworkAddress()).append("]\n")
    181                    .append("Broadcast:\t[").append(getBroadcastAddress()).append("]\n")
    182                     .append("First Address:\t[").append(getLowAddress()).append("]\n")
    183                     .append("Last Address:\t[").append(getHighAddress()).append("]\n")
    184                     .append("# Addresses:\t[").append(getAddressCount()).append("]\n");
    185                return buf.toString();
    186            }
    187        }
    188
    189        /**
    190         * Return a {@link SubnetInfo} instance that contains subnet-specific statistics
    191         * @return new instance
    192         */
    193        public final SubnetInfo getInfo() { return new SubnetInfo(); }
    194
    195        /*
    196         * Initialize the internal fields from the supplied CIDR mask
    197         */
    198        private void calculate(String mask) {
    199            Matcher matcher = cidrPattern.matcher(mask);
    200
    201            if (matcher.matches()) {
    202                address = matchAddress(matcher);
    203
    204                /* Create a binary netmask from the number of bits specification /x */
    205                int cidrPart = rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS);
    206                for (int j = 0; j < cidrPart; ++j) {
    207                    netmask |= (1 << 31-j);
    208                }
    209
    210                /* Calculate base network address */
    211                network = (address & netmask);
    212
    213                /* Calculate broadcast address */
    214                broadcast = network | ~(netmask);
    215            }
    216            else
    217                throw new IllegalArgumentException("Could not parse [" + mask + "]");
    218        }
    219
    220        /*
    221         * Convert a dotted decimal format address to a packed integer format
    222         */
    223        private int toInteger(String address) {
    224            Matcher matcher = addressPattern.matcher(address);
    225            if (matcher.matches()) {
    226                return matchAddress(matcher);
    227            }
    228            else
    229                throw new IllegalArgumentException("Could not parse [" + address + "]");
    230        }
    231
    232        /*
    233         * Convenience method to extract the components of a dotted decimal address and
    234         * pack into an integer using a regex match
    235         */
    236        private int matchAddress(Matcher matcher) {
    237            int addr = 0;
    238            for (int i = 1; i <= 4; ++i) {
    239                int n = (rangeCheck(Integer.parseInt(matcher.group(i)), -1, 255));
    240                addr |= ((n & 0xff) << 8*(4-i));
    241            }
    242            return addr;
    243        }
    244
    245        /*
    246         * Convert a packed integer address into a 4-element array
    247         */
    248        private int[] toArray(int val) {
    249            int ret[] = new int[4];
    250            for (int j = 3; j >= 0; --j)
    251                ret[j] |= ((val >>> 8*(3-j)) & (0xff));
    252            return ret;
    253        }
    254
    255        /*
    256         * Convert a 4-element array into dotted decimal format
    257         */
    258        private String format(int[] octets) {
    259            StringBuilder str = new StringBuilder();
    260            for (int i =0; i < octets.length; ++i){
    261                str.append(octets[i]);
    262                if (i != octets.length - 1) {
    263                    str.append(".");
    264                }
    265            }
    266            return str.toString();
    267        }
    268
    269        /*
    270         * Convenience function to check integer boundaries.
    271         * Checks if a value x is in the range (begin,end].
    272         * Returns x if it is in range, throws an exception otherwise.
    273         */
    274        private int rangeCheck(int value, int begin, int end) {
    275            if (value > begin && value <= end) // (begin,end]
    276                return value;
    277
    278            throw new IllegalArgumentException("Value [" + value + "] not in range ("+begin+","+end+"]");
    279        }
    280
    281        /*
    282         * Count the number of 1-bits in a 32-bit integer using a divide-and-conquer strategy
    283         * see Hacker's Delight section 5.1
    284         */
    285        int pop(int x) {
    286            x = x - ((x >>> 1) & 0x55555555);
    287            x = (x & 0x33333333) + ((x >>> 2) & 0x33333333);
    288            x = (x + (x >>> 4)) & 0x0F0F0F0F;
    289            x = x + (x >>> 8);
    290            x = x + (x >>> 16);
    291            return x & 0x0000003F;
    292        }
    293
    294        /* Convert two dotted decimal addresses to a single xxx.xxx.xxx.xxx/yy format
    295         * by counting the 1-bit population in the mask address. (It may be better to count
    296         * NBITS-#trailing zeroes for this case)
    297         */
    298        private String toCidrNotation(String addr, String mask) {
    299            return addr + "/" + pop(toInteger(mask));
    300        }
    301    }