如何在Python中从2个ip地址计算网络掩码 [英] How to calculate netmask from 2 ip adresses in Python
本文介绍了如何在Python中从2个ip地址计算网络掩码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个范围内的第一个和最后一个ip地址,我如何计算Python中的子网掩码?
How can I calculate the subnetmask in Python if I have the first and the last ip adresses in a range?
我希望网络掩码为例如255.255.255.0。
I want the netmask as e.g. 255.255.255.0.
谢谢;)
推荐答案
说我们有... ...
Say that we have...
def ip_to_int(a, b, c, d):
return (a << 24) + (b << 16) + (c << 8) + d
然后你可以让代表做几个XOR。例如。
Then you can have the representation doing a few XORs. Eg.
>>> bin(0xFFFFFFFF ^ ip_to_int(192, 168, 1, 1) ^ ip_to_int(192, 168, 1, 254))
'0b11111111111111111111111100000000'
所以:
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 << (8*n))) >> 8*n for n in (3, 2, 1, 0)]
>>> mask([192, 168, 1, 1], [192, 168, 1, 254])
[255L, 255L, 255L, 0L]
这篇关于如何在Python中从2个ip地址计算网络掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文