如何在Python中从2个IP地址计算网络掩码

发布于 2024-12-27 06:42:04 字数 99 浏览 4 评论 0原文

如果我有某个范围内的第一个和最后一个 ip 地址,如何在 Python 中计算子网掩码?

我希望网络掩码为例如 255.255.255.0。

谢谢 ;)

How can I calculate the subnetmask in Python if I have the first and the last ip adresses in a range?

I want the netmask as e.g. 255.255.255.0.

Thanks ;)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谈下烟灰 2025-01-03 06:42:04

假设我们有...

def ip_to_int(a, b, c, d):
    return (a << 24) + (b << 16) + (c << 8) + d

那么您可以让表示进行一些异或运算。例如。

>>> 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 << off)) >> off for off in (24, 16, 8, 0)]

>>> mask([192, 168, 1, 1], [192, 168, 1, 254])
[255L, 255L, 255L, 0L]

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 << off)) >> off for off in (24, 16, 8, 0)]

>>> mask([192, 168, 1, 1], [192, 168, 1, 254])
[255L, 255L, 255L, 0L]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文