[英]How to calculate netmask from 2 ip adresses in Python
How can I calculate the subnetmask in Python if I have the first and the last ip adresses in a range?如果我有一个范围内的第一个和最后一个 ip 地址,如何在 Python 中计算子网掩码?
I want the netmask as eg 255.255.255.0.我想要网络掩码,例如 255.255.255.0。
Thanks ;)谢谢 ;)
Say that we have...说我们有...
def ip_to_int(a, b, c, d):
return (a << 24) + (b << 16) + (c << 8) + d
Then you can have the representation doing a few XORs.然后你可以让表示做一些 XOR。 Eg.例如。
>>> bin(0xFFFFFFFF ^ ip_to_int(192, 168, 1, 1) ^ ip_to_int(192, 168, 1, 254))
'0b11111111111111111111111100000000'
So:所以:
def mask(ip1, ip2):
"ip1 and ip2 are lists of 4 integers 0-255 each"
m = 0xFFFFFFFF ^ ip_to_int(*ip1) ^ ip_to_int(*ip2)
return [(m & (0xFF << off)) >> off for off in (24, 16, 8, 0)]
>>> mask([192, 168, 1, 1], [192, 168, 1, 254])
[255L, 255L, 255L, 0L]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.