Created
July 10, 2019 15:24
-
-
Save belyaev-pa/8610e37a5136b6407285523ab23a3e5b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct | |
import socket | |
def ip2int(addr): | |
return struct.unpack("!I", socket.inet_aton(addr))[0] | |
def int2ip(addr): | |
return socket.inet_ntoa(struct.pack("!I", addr)) | |
def get_range(addr, mask): | |
addr = addr.split('_') | |
if len(addr) != 4: | |
return 'Invalid cidr' | |
for i in addr: | |
if int(i) > 255: | |
return 'Invalid cidr' | |
addr = '.'.join(addr) | |
first = ip2int(addr) & (-1 << 32 - mask) | |
last = first + pow(2, 32 - mask) - 1 | |
return {'first_ip': int2ip(first + 1), 'last_ip': int2ip(last)} | |
def check_in_range(addr_1, addr_2, mask): | |
addr_1 = addr_1.split('_') | |
addr_2 = addr_2.split('_') | |
if len(addr_1) != 4 or len(addr_2) != 4: | |
return 'Invalid cidr' | |
for i in addr_1: | |
if int(i) > 255: | |
return 'Invalid cidr' | |
for i in addr_2: | |
if int(i) > 255: | |
return 'Invalid cidr' | |
addr_1 = '.'.join(addr_1) | |
addr_2 = '.'.join(addr_2) | |
first = ip2int(addr_2) & (-1 << 32 - mask) | |
last = first + pow(2, 32 - mask) - 1 | |
if ip2int(addr_1) > first and ip2int(addr_1) < last: | |
return True | |
else: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment