Last active
August 29, 2015 14:10
-
-
Save tywtyw2002/9d09e22536c661fde556 to your computer and use it in GitHub Desktop.
Get ip block from several ip address
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
from functools import reduce | |
from math import log, ceil | |
def x(ip): | |
ip_set = ip.split(".") | |
int_ip = sum([int(ip_set[-i]) << (i - 1) * 8 for i in xrange(1, 5)]) | |
return int_ip | |
def r_x(int_ip): | |
return "%d.%d.%d.%d" % ((int_ip & 0xFF000000) >> 24, | |
(int_ip & 0x00FF0000) >> 16, | |
(int_ip & 0x0000FF00) >> 8, | |
int_ip & 0x000000FF) | |
def get_result(l): | |
int_ip_set = map(x, l) | |
mask = reduce(lambda x, y: x ^ y, int_ip_set) | |
mask = int(ceil(log(mask, 2))) | |
print "%s/%d" % (r_x(x(l[0]) & (2 ** 32 - 1) << mask), (32 - mask)) | |
input = ['104.223.130.170', '104.223.134.229'] | |
input2 = ['104.127.92.146', '104.127.92.246', | |
'104.127.93.119', '104.127.94.204'] | |
get_result(input) | |
get_result(input2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment