Python网络/cidr计算

2024-10-01 15:43:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个嵌入式网络设备(基于linux),遇到了动态构建守护进程conf文件的需要。因此,我需要能够在构建conf文件的python代码中进行一些网络地址计算。我不是一个程序员,所以我担心我写了一个模块,一旦设备开始发货,它将无法正常工作。在

以下是我到目前为止所拥有的,它与我在这个网站和谷歌上找到的东西真的拼凑在一起。在

有没有更好的方法来查找网络接口的网络地址和cidr?将网络掩码转换为bin str并计算1似乎很不雅观。在

import socket
import fcntl
import struct

SIOCGIFNETMASK = 0x891b
SIOCGIFADDR = 0x8915

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def _GetIfaceMask(iface):
    return struct.unpack('L', fcntl.ioctl(s, SIOCGIFNETMASK, struct.pack('256s', iface))[20:24])[0]

def _GetIfaceAddr(iface):
    return struct.unpack('L', fcntl.ioctl(s, SIOCGIFADDR, struct.pack('256s', iface[:15]))[20:24])[0]

def GetIfaceNet(iface):
    net_addr = _GetIfaceAddr(iface) & _GetIfaceMask(iface)
    return socket.inet_ntoa(struct.pack('L', net_addr))

def GetIfaceCidr(iface):
    bin_str = bin(_GetIfaceMask(iface))[2:]
    cidr = 0
    for c in bin_str:
        if c == '1':  cidr += 1
    return cidr

谢谢你的意见,我真的有点迷茫。如果这里不是此类反馈的地方,请让我知道。在


Tags: 文件importreturnbinconfdefsocketstruct
2条回答

您可以检查iptools python模块http://code.google.com/p/python-iptools/它可以从long格式转换为点式ip格式,反之亦然。在

这可以用Hamming-weight算法来解决。从How to count the number of set bits in a 32-bit integer?盗取并翻译成Python:

def number_of_set_bits(x):
    x -= (x >> 1) & 0x55555555
    x = ((x >> 2) & 0x33333333) + (x & 0x33333333)
    x = ((x >> 4) + x) & 0x0f0f0f0f
    x += x >> 8
    x += x >> 16
    return x & 0x0000003f

另一个更具可读性的解决方案(但运行在O(log x))中:

^{pr2}$

相关问题 更多 >

    热门问题