Python Network / cidr calculations

I am working on creating an embedded network device (based on Linux) and have encountered the need to dynamically create confon daemon files. Thus, I need to be able to perform network address calculations in python code that will create conf files. I'm not a programmer, so I'm afraid I wrote a module that will not function, as I hoped, when the device starts delivery.

Below is what I have so far, it really is assembled along with what I could find on this site and on Google.

Is there a better way to find the network address and cidr for the network interface? Converting the netmask to a bin string and counting 1 seems rather inelegant.

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

, . , , .

+3
2

iptools python module http://code.google.com/p/python-iptools/, long to dotted ip .

+2

, . 32- ? 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)):

def number_of_set_bits(x):
    n = 0
    while x:
        n += x & 1
        x = x >> 1
    return n
+4

Source: https://habr.com/ru/post/1790274/


All Articles