Thursday, May 27, 2010

Getting IP Address/Interfaces with Python

# easy_install netifaces

in python shell:

// list all interfaces

>>> import netifaces
>>> netifaces.interfaces()

['lo0', 'gif0', 'stf0', 'en0', 'fw0', 'en1', 'vboxnet0']
>>>

// now get the addresses only for AF_INET

>>> for iface in netifaces.interfaces():
...     if netifaces.AF_INET in netifaces.ifaddresses(iface) and\
...     'addr' in netifaces.ifaddresses(iface)[netifaces.AF_INET][0]:
...             print iface, netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
... 
lo0 127.0.0.1
en0 192.168.2.1
en1 192.168.1.2
>>>

No comments: