Skip to content

Instantly share code, notes, and snippets.

@maguec
Created December 18, 2019 19:13
Show Gist options
  • Save maguec/4bc2f15ec191d135e1117cf6771e8c77 to your computer and use it in GitHub Desktop.
Save maguec/4bc2f15ec191d135e1117cf6771e8c77 to your computer and use it in GitHub Desktop.
Check to see if an IP address is in a range in Redis
#!/usr/bin/python3
import redis, ipaddress
r = redis.Redis(host='localhost', port=6379)
def ip2long(ip):
"""
Convert an IP string to long
"""
return int(ipaddress.ip_address(ip))
def getbclass(ip):
"""
Return the Class B for an address
"""
return '.'.join(ip.split('.')[0:2])
def fillincidr(cidr):
"""
takes a CIDR range and adds it to the sorted sets
"""
net4 = ipaddress.ip_network(cidr)
bclass = getbclass(str(net4.network_address))
r.zadd(bclass, {
cidr+"_min": int(net4.network_address),
cidr+"_max": int(net4.broadcast_address)
})
def get_cidr(ip):
"""
Determine if we have a known ip from a range
"""
bclass = getbclass(ip)
pipe = r.pipeline()
pipe.zrevrangebyscore(bclass, ip2long(ip), '-inf', start=0, num=1)
pipe.zrangebyscore(bclass, ip2long(ip), '+inf', start=0, num=1)
results = pipe.execute()
try:
max = results[0][0].decode("utf-8")
min = results[1][0].decode("utf-8")
if max.split('_')[0] == min.split('_')[0]:
return min.split('_')[0]
else:
return(-1)
except:
return(-1)
myrange = "10.10.0.0/24"
myrange1 = "10.10.1.0/24"
fillincidr(myrange)
fillincidr(myrange1)
myipbad = "10.10.2.123"
myipgood = "10.10.0.255"
print(myipgood, get_cidr(myipgood))
print(myipbad, get_cidr(myipbad))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment