Best way to get ip address
pfortin at pfortin.com
Fri Sep 10 00:55:44 CEST 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)
> # 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
# returns: ('hostname.domain', ['hostname'], ['192.168.0.2'])
ip = socket.gethostbyaddr(socket.gethostname())[-1]
Gets the only list item of the last tuple item -- no calls to str() or
getting cute with the list's "[...]"
More information about the Python-list