I have multiple Network Interface Cards on my computer, each with its own IP address.
When I use gethostbyname(gethostname())
from Python’s (built-in) socket
module, it will only return one of them. How do I get the others?
Advertisement
Answer
Use the netifaces
module. Because networking is complex, using netifaces can be a little tricky, but here’s how to do what you want:
JavaScript
x
17
17
1
>>> import netifaces
2
>>> netifaces.interfaces()
3
['lo', 'eth0']
4
>>> netifaces.ifaddresses('eth0')
5
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]}
6
>>> for interface in netifaces.interfaces():
7
print netifaces.ifaddresses(interface)[netifaces.AF_INET]
8
9
[{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}]
10
[{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}]
11
>>> for interface in netifaces.interfaces():
12
for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]:
13
print link['addr']
14
15
127.0.0.1
16
10.0.0.2
17
This can be made a little more readable like this:
JavaScript
1
9
1
from netifaces import interfaces, ifaddresses, AF_INET
2
3
def ip4_addresses():
4
ip_list = []
5
for interface in interfaces():
6
for link in ifaddresses(interface)[AF_INET]:
7
ip_list.append(link['addr'])
8
return ip_list
9
If you want IPv6 addresses, use AF_INET6
instead of AF_INET
. If you’re wondering why netifaces
uses lists and dictionaries all over the place, it’s because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.