Getting network interfaces in Python

Posted on Fri 30 December 2011 in Sysadmin

Here’s a small Python script/module I put together to list all network interfaces on the current server (tested on Linux only!) in a format that easily lets me convert between name, index and address of an interface.

The code is based on from pydlnadms, but I have refactored it a tiny bit and removed stuff I didn’t need.

With this module, I can write things like:

>>> import socket
>>> import getnifs
>>> nifs = getnifs.get_network_interfaces()
>>> [ni.index for ni in nifs if == 'eth0'][2]
>>> [ for ni in nifs if ni.index == 1]['lo']
>>> [ for ni in nifs if '' in ni.addresses.values()]['lo']

…which is exactly what I was looking for!