Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user's IP address is in a range of IP's

In my Python application I have an array of IP address strings which looks something like this:

[
    "50.28.85.81-140", // Matches any IP address that matches the first 3 octets, and has its final octet somewhere between 81 and 140
    "26.83.152.12-194" // Same idea: 26.83.152.12 would match, 26.83.152.120 would match, 26.83.152.195 would not match
]

I installed netaddr and although the documentation seems great, I can't wrap my head around it. This must be really simple - how do I check if a given IP address matches one of these ranges? Don't need to use netaddr in particular - any simple Python solution will do.

like image 234
tylerl Avatar asked Mar 10 '23 05:03

tylerl


1 Answers

The idea is to split the IP and check every component separately.

mask = "26.83.152.12-192"
IP = "26.83.152.19"
def match(mask, IP):
   splitted_IP = IP.split('.')
   for index, current_range in enumerate(mask.split('.')):
      if '-' in current_range:
         mini, maxi = map(int,current_range.split('-'))
      else:
         mini = maxi = int(current_range)
      if not (mini <= int(splitted_IP[index]) <= maxi):
         return False
   return True
like image 50
Faibbus Avatar answered Mar 20 '23 11:03

Faibbus