How to calculate netmask from 2 ip adresses in Python

冷暖自知 提交于 2019-12-08 08:51:27

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. 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 << (8*n))) >> 8*n for n in (3, 2, 1, 0)]

>>> mask([192, 168, 1, 1], [192, 168, 1, 254])
[255L, 255L, 255L, 0L]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!