get the IP address of a host

none "j.p.t.j.berends\" at (none)
Wed Jan 5 10:59:11 EST 2005

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.

More information about the Python-list mailing list