All Courses

Python - Network Interface

Neha Kumawat

2 years ago

Python - Network Interface | insideAIML
Table of Contents
  • Checking all networking Interface in a computer
  • netifaces
          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):
        outbytes = struct.unpack('iL', fcntl.ioctl(
            0x8912,  # SIOCGIFCONF
            struct.pack('iL', _bytes, names.buffer_info()[0])
        if outbytes == _bytes:
            max_possible *= 2
    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
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.


  • 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')

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': '', 'addr': '', 'netmask': ''}], 10: [{'addr': '::1', 'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128'}]}


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

Like the Blog, then Share it with your friends and colleagues to make this AI community stronger. 
To learn more about nuances of Artificial Intelligence, Python Programming, Deep Learning, Data Science and Machine Learning, visit our insideAIML blog page.
Keep Learning. Keep Growing. 

Submit Review