Alastair’s Place

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

Getting Network Addresses From Python

It’s been irritating me for ages that it isn’t possible to straightforwardly get the network address(es) of the machine you’re running on from a Python program.

Well, if you’re running Mac OS X, or probably some of the various other UNIX-like systems, now you can (here’s the source code).

Here’s a quick example of how to use it:

>>> import netifaces
>>> netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']
>>> netifaces.ifaddresses('en0')
{18: [{'addr': '00:12:34:56:78:9a'}], 2: [{'broadcast':
 '', 'netmask': '', 'addr': ''}],
 30: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr':

Note that presently this has only been tested on Mac OS X (the SIOCGIFxxx ioctl()s have been tested, apart from SIOCGIFHWADDR, which doesn’t exist on OS X).

Note also that it won’t work on Windows. You’d need to use the Windows Sockets functions to get similar functionality on Windows, I think.

Update (2007/03/18)

It works on Windows now too! There are also pre-built binary versions for Windows (Python 2.4, Python 2.5), and also Mac OS X. But do yourself a favour and use easy_install:

easy_install netifaces

(You can get easy_install from the PEAK Developers’ Center if you don’t have it already.)

The Windows code can currently only return IPv4 addresses and MAC addresses; also, since Windows doesn’t define AF_LINK, I’ve defined it in netifaces for compatibility.

Update (2007/03/20)

I’ve updated the code so that it builds on Windows with MSVC as well as with GCC. Also, I’ve added support for Linux (which lacks the sa_len member in struct sockaddr, making getifaddrs() somewhat harder to use sensibly).

I’ve also build some more binaries:

Python 2.4/Mac OS X 10.4

Python 2.4/Win32

Python 2.5/Win32

Python 2.4/x86 Linux

Python 2.5/x86 Linux

Update (2008/02/24)

Christian Kauhaus pointed out that the PPP interface on Linux sometimes results in a getifaddrs() record with no address, which causes a crash. Also, Python’s egg selection mechanism meant that the Linux binaries were a nuisance for those with older versions of Linux, so I’ve removed them.

Update (2009/03/09)

Olivier Bourdon very kindly contributed some changes to make netifaces work better on Solaris. I have now merged these in, so Solaris users should no longer need to use the separate patches listed in the links below.

I have also build new binaries for Windows users using Python 2.5 and Python 2.6. If you are still running Python 2.4, please use the older links above (the old version works just fine).

Update 2011-10-14

I’ve moved netifaces to its own page. Please go there to download it.