Uses the Linux SIOCGIFADDR ioctl to find the IP address associated with a network interface, given the name of that interface, e.g. "eth0". The address is returned as a string containing a dotted quad.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import socket import fcntl import struct def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) >>> get_ip_address('lo') '127.0.0.1' >>> get_ip_address('eth0') '220.127.116.11'
People often ask how to get the "IP address of a computer". The question is misguided; computers don't usually have IP addresses themselves, but they often have one or more network interfaces which do. This recipe is a suitable answer in some cases, but of course, the best solution depends on what the programmer is trying to accomplish. Sometimes what they want is to find out their system's address from the point of view of a peer host elsewhere on a network, in which case they should just make a socket connection to that host and call getsockname() on the socket.
This may be the fastest way to find out what ifconfig would report as the IP address for an interface, though. It should certainly be faster than actually running ifconfig and parsing the output.
Users asking which interface names to check may want to see my all_interfaces() recipe, just posted.
This solution will probably only work on Linux, due to its dependence on certain C structures being of a certain size and layout, and on SIOCGIFADDR being 0x8915. It will possibly not even work on all versions of Linux, although it does on 2.4 and 2.6. If it doesn't work on other Unixes, it could probably be adjusted to work. Comments or suggestions on better portability are welcomed.