Nilani Algiriyage
Nilani Algiriyage

Reputation: 35666

Python regex to match IP range

I want to match IP range using a Python regex.

For Ex. the google bot IP range as follow

66.249.64.0 - 66.249.95.255

re.compile(r"66.249.\d{1,3}\.\d{1,3}$")

I can not figure out how to do this? I found this one done using Java.

Upvotes: 1

Views: 1385

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can use this:

re.compile(r"66\.249\.(?:6[4-9]|[78]\d|9[0-5])\.\d{1,3}$")

if you are motivated you can replace \d{1,3} by :

(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

Explanation:

A regex engine doesn't know what a numeric range is. The only way to describe a range is to write all the possibilities with alternations:

6[4-9]  |  [78][0-9]  |  9[0-5] 

6          can be followed by    4 to 9   --> 64 to 69
7 or 8     can be followed by    0 to 9   --> 70 to 89
9          can be followed by    0 to 5   --> 90 to 95 

Upvotes: 1

Joel Cornett
Joel Cornett

Reputation: 24788

Use socket.inet_aton:

import socket
ip_min, ip_max = socket.inet_aton('66.249.64.0'), socket.inet_aton('66.249.95.255')

if ip_min <= socket.inet_aton('66.249.63.0') <= ip_max:
    #do stuff here

Upvotes: 1

njzk2
njzk2

Reputation: 39406

The last digit is:

[01]?\d{1,2}|2[0-4]\d|25[0-5]

The 3rd digit is:

6[4-9])|[78]\d|9[0-5]

Upvotes: 0

Related Questions