Question

I need a regex that I haven't been able to figure out:

How do I take something like this:

60.70.80.90/25

And turn it into a regex that will match IPs in that range?

That IP address is just a dummy; the actual IP range is different. Is there a way to turn that into a regex, without enumerating every single address in that range? For example, I know I could do this:

60\.70\.80\.91|...

But I'd rather not have to enumerate all those addresses. Anyone able to figure out a regex for this?

This will be used in an IIS rewrite rule to whitelist specific IP's, and deny access to all others.

EDIT: If you have a better idea for whitelisting IP's other than what I've suggested, feel free to suggest accordingly.

Was it helpful?

Solution

<Limit GET POST HEAD>
  Order Deny,Allow
  Deny  from all
  Allow from 60.70.80.90/25
</Limit>

OTHER TIPS

A regex is entirely the wrong tool for this task. Regexes are good for text manipulation; netmask math is a math operation. It is possible to do this with a regex, but it's very ugly, very confusing, and very inefficient!

Your best bet is to use a library for IP and network manipulations, such as Net::CIDR for Perl. If you can't use one for some reason, do the manipulations yourself:

  1. Convert the dotted-decimal format into its numeric equivalent:

    60.70.80.90/25 -> 1011241050/4294967168
    
  2. Convert the IP to be matched into its numeric form:

    1.2.3.4 -> 16909030
    
  3. AND the target IP against the netmask:

    16909030 & 4294967168 = 16908928
    
  4. AND the whitelisted IP against he netmask:

    1011241050 & 4294967168 = 1011240960
    
  5. If the results match, it's a match:

    16908928 == 1011240960 ? Then whitelist match

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top