get the IP address of a host

Lee Harr lee at example.com
Wed Jan 5 17:41:15 EST 2005


On 2005-01-05, none <""> wrote:
> I want to determine the outside (non local, a.k.a. 127.0.0.x) ip 
> addresses of my host. It seems that the socket module provides me with 
> some nifty tools for that but I cannot get it to work correctly it seems.
>
> Can someone enlightened show a light on this:
>
> import socket
> def getipaddr(hostname='default'):
>      """Given a hostname, perform a standard (forward) lookup and return
>      a list of IP addresses for that host."""
>      if hostname == 'default':
>          hostname = socket.gethostname()
>      ips = socket.gethostbyname_ex(hostname)[2]
>      return [i for i in ips if i.split('.')[0] != '127'][0]
>
> It does not seem to work on all hosts. Sometimes socket.gethostbyname_ex 
> only retrieves the 127.0.0.x ip adresses of the local loopback. Does 
> someone has a more robust solution?
>
> Targetted OS'es are Windows AND linux/unix.


I found that the socket solutions only work if your
DNS entries are correct ... which in my case was not
true. So I came up with this:


import commands


ifconfig = '/sbin/ifconfig'
# name of ethernet interface
iface = 'eth0'
# text just before inet address in ifconfig output
telltale = 'inet addr:'


def my_addr():
    cmd = '%s %s' % (ifconfig, iface)
    output = commands.getoutput(cmd)

    inet = output.find(telltale)
    if inet >= 0:
        start = inet + len(telltale)
        end = output.find(' ', start)
        addr = output[start:end]
    else:
        addr = ''

    return addr



Basically, it scrapes the output from ifconfig for the
actual address assigned to the interface. Works perfectly
on FreeBSD and Linux (given the correct configuration).



More information about the Python-list mailing list