Best way to get ip address

John Lenton john at grulic.org.ar
Thu Sep 9 19:19:16 EDT 2004


On Thu, Sep 09, 2004 at 12:07:42PM -0700, Darren Kirby wrote:
> Hello list:
> 
> I am writing a small app in python which tracks the kernel banner at 
> kernel.org and downloads newer kernel version(s) (if there are any).
> 
> I am using GeoIP to set the download to a local mirror if there is one. This 
> is what I use to get the local IP address:
> 
> 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?
> 
> Another issue is that if the user is behind a NAT firewall or somesuch and 
> uses a private network address then the whole GeoIP code is moot. I was 
> thinking that if this is the case then the app could check for the default 
> gateway of the machine and use that IP instead, but of course the gateway may 
> just be another private network IP address. Does anyone have some ideas on 
> how I could make this code useful with a private IP address?

this is more convoluted, and depends on a third party, but I find it's
the most reliable way to find out what you seem to be wanting:

    re.findall('[0-9.]+',
               urllib.urlopen('http://checkip.dyndns.org/').read())[-1]

there are several apps out there that depend on checkip.dyndns.org,
and it's a published service, so it shouldn't be changing too often.

HTH.

-- 
John Lenton (john at grulic.org.ar) -- Random fortune:
You love your home and want it to be beautiful.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20040909/f0e7222b/attachment.sig>


More information about the Python-list mailing list