Python - Network Interface

Neha Kumawat

10 months ago

When we have multiple interfaces in a machine we need to keep track of their names, status, etc. In Python we can list the interfaces and their status.

Checking all networking Interface in a computer

Here's a version that works on python 3.4, both 32- and 64-bits, returns both the interface name and its address, and as a bonus isn't limited to 128 interfaces (although I don't believe it's really going to be a problem for anyone)
import socket
import fcntl
import struct
import array
import sys

def all_interfaces():
    is_64bits = sys.maxsize > 2**32
    struct_size = 40 if is_64bits else 32
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    max_possible = 8 # initial value
    while True:
        _bytes = max_possible * struct_size
        names = array.array('B')
        for i in range(0, _bytes):
            names.append(0)
        outbytes = struct.unpack('iL', fcntl.ioctl(
            s.fileno(),
            0x8912,  # SIOCGIFCONF
            struct.pack('iL', _bytes, names.buffer_info()[0])
        ))[0]
        if outbytes == _bytes:
            max_possible *= 2
        else:
            break
    namestr = names.tostring()
    ifaces = []
    for i in range(0, outbytes, struct_size):
        iface_name = bytes.decode(namestr[i:i+16]).split('\0', 1)[0]
        iface_addr = socket.inet_ntoa(namestr[i+20:i+24])
        ifaces.append((iface_name, iface_addr))

    return ifaces

Example

In the below example we use the python module netifaces which gives the details of the interfaces and their status. The methods used are very simple and straight forward.

netifaces

  • A portable third-party library in Python to enumerate network interfaces on local machine.
  • Historically it has been difficult to straightforwardly get the network address(es) of the machine on which your Python scripts are running without compromising the portability of your script.
  • netifaces takes care of enumerating interfaces, network addresses and also preserves the portability(works on all *nix systems atleast).

import netifaces

print (netifaces.interfaces())


print (netifaces.ifaddresses('lo'))

print (netifaces.AF_LINK)

addrs = netifaces.ifaddresses('ens33')
print(addrs[netifaces.AF_INET])


print(addrs[netifaces.AF_LINK])
When we run the above program, we get the following output

# Result

['lo', 'ens33']
{17: [{'peer': '00:00:00:00:00:00', 'addr': '00:00:00:00:00:00'}], 2: [{'peer': '127.0.0.1', 'addr': '127.0.0.1', 'netmask': '255.0.0.0'}], 10: [{'addr': '::1', 'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128'}]}

17

[{'netmask': '255.255.255.0', 'addr': '192.168.232.128', 'broadcast': '192.168.232.255'}]
[{'addr': '00:0c:29:ea:13:0a', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]

learn more on python programming InsideAIML.

Submit Review