I’m working on making a simple server application with python, and I’m trying to get the IP to bind the listening socket to. An example I looked at uses this:
HOST = gethostbyaddr(gethostname())
With a little more processing after this, it should give me just the host IP as a string. This should return the IPv4 address. But when I run this code, it returns my IPv6 address. Why does it do this and how can I get my IPv4 address?
If its relevant, I’m using windows vista and python 2.5
Getting your IP address is harder than you might think.
Check this answer I gave for the one reliable way I’ve found.
Here’s what the answer says in case you don’t like clicking on things:
Use the
netifacesmodule. Because networking is complex, using netifaces can be a little tricky, but here’s how to do what you want:This can be made a little more readable like this:
If you want IPv6 addresses, use
AF_INET6instead ofAF_INET. If you’re wondering whynetifacesuses 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.