ayumi
ayumi

Reputation: 129

How can I make a regular expression for IP address with Subnetmask?

I have IP address list like this:

180.183.0.0/16
180.210.216.0/22
180.214.192.0/19
182.52.0.0/15
...(400 more)

How can I make a regular expression for IP address with Subnetmask?

Why I want to get this.

I have a website with Load Balancer(I can't change any config in server), my client wants to deny access from specific country access. I use .htaccess like this.

SetEnvIf X-Forwarded-For "59\.(5[6-9]|6[0-1])\.[0-9]+\." denyIP
order allow,deny
allow from all
deny from env=denyIP

Upvotes: 3

Views: 7986

Answers (1)

Ro Yo Mi
Ro Yo Mi

Reputation: 15010

Given the list of address in your sample text these expressions will match the requested ranges by using alternation to match numeric ranges. Unfortunately they'll need to be constructed individually because of how a regular expression doesn't really evaluate the text. To match a 182.52 or 182.53 string you'd use a regex which contains the desired sub-strings and it would look like 182.5[23].

  • 180.183.0.0/16 has a range 180.183.0.1 - 180.183.255.254
    • ^180\.183\.(?:[0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.(?:[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-4])$ enter image description here
  • 180.210.216.0/22 has a range 180.183.0.1 - 180.183.3.254
    • ^180\.210\.[0-3]\.(?:[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-4])$ enter image description here
  • 180.214.192.0/19 has a range 180.183.0.1 - 180.183.31.254
    • ^180\.214\.(?:[0-9]|[12][0-9]|3[01])\.(?:[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-4])$ enter image description here
  • 182.52.0.0/15 has a range 182.52.0.1 - 182.53.255.254
    • ^182\.5[23]\.(?:[0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.(?:[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-4])$ enter image description here

Upvotes: 4

Related Questions