Skip to content

Instantly share code, notes, and snippets.

@mvanderlee
Created February 28, 2018 01:00
Show Gist options
  • Save mvanderlee/b2f8127805229a0689aa83b2978073a9 to your computer and use it in GitHub Desktop.
Save mvanderlee/b2f8127805229a0689aa83b2978073a9 to your computer and use it in GitHub Desktop.
IPv4 helper methods.
def uint(i):
return 0xffffffff & i
def IP2Int(ip):
o = map(int, ip.split('.'))
res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
return res
def Int2IP(ipnum):
o1 = int(ipnum / 16777216) % 256
o2 = int(ipnum / 65536) % 256
o3 = int(ipnum / 256) % 256
o4 = int(ipnum) % 256
return '%(o1)s.%(o2)s.%(o3)s.%(o4)s' % locals()
def isIPInCIDR(ip, cidr):
parts = cidr.split('/')
cidr_ip = parts[0]
cidr_maskbit = parts[1]
int_cidr_ip = IP2Int(cidr_ip)
int_mask = 0xffffffff << (32 - int(cidr_maskbit))
int_network = uint(int_cidr_ip & int_mask)
int_broadcast = uint(int_network | (~int_mask))
# print '{} = {}'.format(int_network, Int2IP(int_network))
# print '{} = {}'.format(int_broadcast, Int2IP(int_broadcast))
int_ip = IP2Int(ip)
# print '{} = {}'.format(int_ip, Int2IP(int_ip))
return int_ip >= int_network and int_ip <= int_broadcast
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment