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:
1 2 3
You can also inspect a particular interface to determine its addresses:
1 2 3 4 5
netifaces sets up constants for all of the address
families, so e.g.:
1 2 3 4 5 6
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
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.