AKZap
AKZap

Reputation: 1211

How to check the IP range by java matcher regular expression

My Current Regular Expression for checking the ip range between: 178.2.1.1 to 178.2.1.254 is as follow:

178.2.1.1.([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])$

Is there any other better expression way to check that.

Upvotes: 2

Views: 3171

Answers (3)

Sean F
Sean F

Reputation: 4595

The open-source IPAddress Java library can provide the answer rather easily, as shown in this code example. Disclaimer: I am the project manager of that library.

public static boolean check(String addressToCheck) {
    return new IPAddressString("178.2.1.1-254").getAddress().
        contains(new IPAddressString(addressToCheck).getAddress());
}

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476537

Regular expression

Assuming you want to match all IP adresses between 178.2.1.1 and 178.2.1.254 (with 178 instead of 1), you can use the following regex:

^178\.2\.1\.([1-9]\d?|1\d{2}|2[0-4]\d|25[0-4])$

Dropping the last 1., using escapes for the dots (\.) and using the anchor in the front of the regex (^).

Bounds checking with a library

But that will not suffice in general. Most IP parsers allow for instance to specify an IP as 127.00.00.01, etc. Furthermore don't forget that nowadays people move to IPv6 which has a completely different syntax. You better do the parsing to an InetAddress in Java as is described here. In case it is an IPv4, you can then simply perform bound checks, like is partly described here:

String       s = "178.2.1.178";
Inet4Address a = (Inet4Address) InetAddress.getByName(s);
byte[]       b = a.getAddress();
int          ip = ((b[0] & 0xFF) << 24) |
                  ((b[1] & 0xFF) << 16) |
                  ((b[2] & 0xFF) << 8)  |
                  ((b[3] & 0xFF) << 0);
int low =  0xb2020101; //equivalent of 178.2.1.1
int high = 0xb20201fe; //equivalent of 178.2.1.254
if(low <= ip && ip <= high) {
    //matches bounds
} else {
    //doesn't match bounds
}

Or as @IanMcLaird suggests, one better uses a BigInteger:

BigInteger addr = new BigInteger(InetAddress.getByName("178.2.1.178").getAddress());
BigInteger low = new BigInteger(InetAddress.getByName("178.2.1.1").getAddress());
BigInteger high = new BigInteger(InetAddress.getByName("178.2.1.254").getAddress());
if(low.compareTo(addr) <= 0 && addr.compareTo(high) <= 0) {
    //in range
} else {
    //not in range
}

Subnets

Please note you can describe the range of your IP with 178.2.1.0/24 since .0 and .255 are special cases, it means the last byte is not significant. In such case we're talking about a subnet and - as @biziclop says - you can use these Apache utils.

Upvotes: 5

runDOSrun
runDOSrun

Reputation: 10985

You need to be careful with "between" as both IPs can have min/max values. You can do something like:

/**
 * check if IP address match pattern
 * 
 * @param pattern
 *            *.*.*.* , 192.168.1.0-255 , *
 * @param address
 *            - 192.168.1.1
 *            address = 10.2.88.12  pattern = *.*.*.*   result: true
 *                address = 10.2.88.12  pattern = *   result: true
 *                address = 10.2.88.12  pattern = 10.2.88.12-13   result: true
 *                address = 10.2.88.12  pattern = 10.2.88.13-125   result: false
 * @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;
}

(Part of aion-emu package )

Upvotes: 3

Related Questions