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
, . , , .