Best way to get ip address

Pierre Fortin pfortin at pfortin.com
Thu Sep 9 18:55:44 EDT 2004


On Thu, 9 Sep 2004 12:07:42 -0700 Darren wrote:

> ip = socket.gethostbyaddr(socket.gethostname())
> # returns:  ('hostname.domain', ['hostname'], ['192.168.0.2'])
> ip = str(ip[2])
> # returns:  "['192.168.0.2']"
> ip = ip[2:-2]
> # returns:  '192.168.0.2'
> 
> This works fine, but seems a little crufty and convoluted, and usually
> when things get crufty it means there is a better way to do it...so is
> there a preferred way of obtaining a local IP address?

When functions return well documented results, I tend to just code like
this:

   # returns:  ('hostname.domain', ['hostname'], ['192.168.0.2'])
   ip = socket.gethostbyaddr(socket.gethostname())[-1][0]

Gets the only list item of the last tuple item -- no calls to str() or
getting cute with the list's "[...]"

Pierre





More information about the Python-list mailing list