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':
'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'}]}
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.
Thanks for the library! It's very useful.
I remarked that when using the library on Linux with a 64bit kernel, the library segfaults. That's either with a 32bit or 64bit libc. I'll try to debug a little when I have time to see where it crashes.