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 getifaddrs.py 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 ni.name == 'eth0'][2]
>>> [ni.name for ni in nifs if ni.index == 1]['lo']
>>> [ni.name for ni in nifs if '127.0.0.1' in ni.addresses.values()]['lo']

…which is exactly what I was looking for!