| Main |

March 12, 2007

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.

March 4, 2007

Lunar Eclipse

Last night there was a lunar eclipse, which I was lucky enough to be able to photograph through my telescope. I was a bit concerned that the weather wouldn’t hold, but the only problem I had was significant dewing in the run up to midnight.

Anyway, I combined the images into a single montage, showing the Moon before the eclipse, then in two stages of partial eclipse, and finally in total eclipse. The orange-red colour of the Moon in the latter two stages was really striking, I think you’ll agree.

Lunar Eclipse Montage

Click on the image for a larger version.