How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
im using following module:
Tested with windows and linux (and doesnt require additional modules for those) intended for use on systems which are in a single IPv4 based LAN.
The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by Alexander. In such cases, you need to manually replace the list with the interface names on your system, or use another solution like netifaces.
A slight refinement of the commands version that uses the IP command, and returns IPv4 and IPv6 addresses:
On Debian (tested) and I suspect most Linux's..
On MS Windows (tested)
This answer is my personal attempt to solve the problem of getting the LAN IP, since
socket.gethostbyname(socket.gethostname())
also returned 127.0.0.1. This method does not require Internet just a LAN connection. Code is for Python 3.x but could easily be converted for 2.x. Using UDP Broadcast:netifaces is available via pip and easy_install. (I know, it's not in base, but it could be worth the install.)
netifaces does have some oddities across platforms:
Here's some netifaces code to play with:
The above code doesn't map an address back to its interface name (useful for generating ebtables/iptables rules on the fly). So here's a version that keeps the above information with the interface name in a tuple:
And, no, I'm not in love with list comprehensions. It's just the way my brain works these days.
The following snippet will print it all out:
Enjoy!
This won't work always (returns
127.0.0.1
on machines having the hostname in/etc/hosts
as127.0.0.1
), a paliative would be what gimel shows, usesocket.getfqdn()
instead. Of course your machine needs a resolvable hostname.