将网络掩码转前缀的代码完整版本,适应v4与v6。 在IPy工具包下,v6不支持使用mask,必须是prefix
ipv4_mask2prefix = lambda mask: sum(bin(int(i, 10)).count('1') for i in mask.split('.'))
ipv6_mask2prefix = lambda mask: sum(bin(int(i, 16)).count('1') for i in mask.split(':'))
mask2prefix = lambda mask: ipv4_mask2prefix(mask) if mask.find(".") > 0 else ipv6_mask2prefix(mask)
>>> mask2prefix("255.255.255.128")
25
>>> mask2prefix('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe')
127