Alastair’s Place

Software development, Cocoa, Objective-C, life. Stuff like that.

Netifaces

Portable access to network interfaces from Python

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.

As a result, when I needed to do this for the first time, I thought it would be best to write a Python module that would work on (at least) Mac OS X and Linux, and maybe other UNIX-like systems too. netifaces is the result.

Here’s a quick example:

List the network interfaces on a machine, using netifaces.
1
2
3
>>> import netifaces
>>> netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']

You can also inspect a particular interface to determine its addresses:

Find the address of interface `en0`.
1
2
3
4
5
>>> netifaces.ifaddresses('en0')
{18: [{'addr': '00:12:34:56:78:9a'}], 2: [{'broadcast':
 '10.255.255.255', 'netmask': '255.0.0.0', 'addr': '10.16.1.4'}],
 30: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr':
 'fe80::123:4567:89ab:cdef%en0'}]}

Additionally, netifaces sets up constants for all of the address families, so e.g.:

Using address family constants
1
2
3
4
5
6
>>> netifaces.ifaddresses('en0')[netifaces.AF_LINK]
[{'addr': '00:12:34:56:78:9a'}]
>>> netifaces.AF_LINK
18
>>> netifaces.address_families[18]
'AF_LINK'

Importantly, the numeric values of address family constants, as well as the precise set available, may change from system to system. AF_LINK will always exist; on platforms where it does not actually exist in the system, it will take the value -1. You can also rely on the existence of AF_INET, but otherwise you should not assume that the system on which you are running supports a particular address family.

The netifaces package works on Windows as well as many UNIX-like platforms; various people have contributed patches for systems I don’t have access to myself. The fastest way to install it is to use easy_install, which you can get from the PEAK Developers’ Center if you don’t already have it. It may also be available as a package on some Linux or BSD distributions.

You can get the source code and various binary packages from PyPI. The source code is now held on Bitbucket.