Python - Get localhost IP

There is a nifty module you can use. Its called netifaces. Just do a pip install netifaces into a virtualenv for testing and try the following code:

import netifaces

interfaces = netifaces.interfaces()
for i in interfaces:
    if i == 'lo':
        continue
    iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
    if iface != None:
        for j in iface:
            print j['addr']

It all depends on your environment. If you only have one interface with one IP address attached to it, you can simply do:

netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']

If you are behind a NAT and want to know your public IP address, you can use something like:

import urllib2

ret = urllib2.urlopen('https://icanhazip.com/')
print ret.read()

Hope this helps.


I generally use this code:

import os
import socket

if os.name != "nt":
    import fcntl
    import struct

    def get_interface_ip(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
                                ifname[:15]))[20:24])

def get_lan_ip():
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith("127.") and os.name != "nt":
        interfaces = [
            "eth0",
            "eth1",
            "eth2",
            "wlan0",
            "wlan1",
            "wifi0",
            "ath0",
            "ath1",
            "ppp0",
            ]
        for ifname in interfaces:
            try:
                ip = get_interface_ip(ifname)
                break
            except IOError:
                pass
    return ip

I don't know it's origin, but it works on Linux/Windows.

Edit:

This code is used by smerlin in this stackoverflow question.