传入ip地址和后缀cidr,返回开始ip与结束ip

ip2long = lambda x: sum([256 ** j * int(i) for j, i in enumerate(x.split('.')[::-1])])
long2ip = lambda x: '.'.join(['{:0>3d}'.format(x // (256 ** i) % 256) for i in range(3, -1, -1)])

def cidr_to_range(ip_cidr):
    ip, cidr = ip_cidr.split('/')
    ip = ip2long(ip)
    cidr = int(cidr)
    start = ip & (-1 << (32 - cidr))
    end = start + 2 ** (32 - cidr) - 1
    return [long2ip(start), long2ip(end)]

print(cidr_to_range('1.2.3.4/24')) # 输出 ['001.002.003.000', '001.002.003.255']

 

posted @ 2022-03-10 22:47  xuecl  阅读(209)  评论(0编辑  收藏  举报