Java IP Address Match checkIPMatching(String pattern, String address)

Here you can find the source of checkIPMatching(String pattern, String address)

Description

check if IP address match pattern

License

Open Source License

Parameter

Parameter Description
pattern *.*.*.* , 192.168.1.0-255 ,
address - 192.168.1.1<BR> <code>address = 10.2.88.12 pattern = *.*.*.* result: true<BR> address = 10.2.88.12 pattern = * result: true<BR> address = 10.2.88.12 pattern = 10.2.88.12-13 result: true<BR> address = 10.2.88.12 pattern = 10.2.88.13-125 result: false<BR></code>

Return

true if address match pattern

Declaration

public static boolean checkIPMatching(String pattern, String address) 

Method Source Code

//package com.java2s;
/**// w  w w.j  a  va  2s .c  o m
 * This file is part of Aion X Emu <aionxemu.com>
 *
 *  This is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This software is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser Public License
 *  along with this software.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * check if IP address match pattern
     *
     * @param pattern *.*.*.* , 192.168.1.0-255 , *
     * @param address - 192.168.1.1<BR>
     *                <code>address = 10.2.88.12  pattern = *.*.*.*   result: true<BR>
     *                address = 10.2.88.12  pattern = *   result: true<BR>
     *                address = 10.2.88.12  pattern = 10.2.88.12-13   result: true<BR>
     *                address = 10.2.88.12  pattern = 10.2.88.13-125   result: false<BR></code>
     * @return true if address match pattern
     */
    public static boolean checkIPMatching(String pattern, String address) {
        if (pattern.equals("*.*.*.*") || pattern.equals("*"))
            return true;

        String[] mask = pattern.split("\\.");
        String[] ip_address = address.split("\\.");
        for (int i = 0; i < mask.length; i++) {
            if (mask[i].equals("*") || mask[i].equals(ip_address[i]))
                continue;
            else if (mask[i].contains("-")) {
                byte min = Byte.parseByte(mask[i].split("-")[0]);
                byte max = Byte.parseByte(mask[i].split("-")[1]);
                byte ip = Byte.parseByte(ip_address[i]);
                if (ip < min || ip > max)
                    return false;
            } else
                return false;
        }
        return true;
    }
}

Related

  1. checkIPv6Match(String ipTemplateList, String ipStr)