Getting the System IP Address with Python

The default Python 2.7.1 distribution has very limited functionality for getting the system IP. If your not willing to install an external module then you really only have one choice… open a socket, establish a connection, and get the active IP from the socket name tuple.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('immersivelabs.com', 0))
s.getsockname()[0]

Although this solution works, it has a few issues. The biggest draw back is that it only returns one of the systems IP addresses. Fortunately, there is a great module called pynetinfo. Install the module using easy_install and then wrap its functionality with the following methods.

import netinfo

def getSystemIfs():
    return netinfo.list_active_devs()

def getSystemIps():
    """ will not return the localhost one """
    IPs = []
    for interface in getSystemIfs():
        if not interface.startswith('lo'):
            ip = netinfo.get_ip(interface)
            IPs.append(ip)
    return IPs

def getIPString():
    """ return comma delimited string of all the system IPs"""
    return ",".join(getSystemIps())

You can now easily get a list or a string containing all the active IP addresses on the system (POSIX Only).