Finding IP address of localhost via socket API (or other API)

Timothy Grant timothy.grant at gmail.com
Wed Aug 6 05:35:02 CEST 2008


On Tue, Aug 5, 2008 at 4:39 PM, Steven D'Aprano
<steve at remove-this-cybersource.com.au> wrote:
> Sorry for replying to the replier (Timothy) instead of the OP (David),
> but the original post seems to have been eaten by my ISP.
>
> On Tue, 05 Aug 2008 15:48:26 -0700, Timothy Grant wrote:
>
>> On Tue, Aug 5, 2008 at 2:50 PM, David York <davideyork at gmail.com> wrote:
>>> Does anybody know how to find the real IP address (e.g.: address
>>> visible to internet) of a machine via Python?  In other words I have a
>>> machine with an IP address something like 192.168.1.5, an address given
>>> to me by a router. The router's address (and thus my machine's address)
>>> to the outside world is something realistic, 123.156.123.156 or
>>> whatever.  How do I get that number?  I've tried
>>> socket.getaddrinfo('localhost', None) but all I get is 127.0.0.1 as
>>> expected.
>>>
>>> How do I find out my machine's IP address as visible to the outside
>>> world? Thanks a lot.
>>>
>>>    David
>>
>> I'm not sure what you are trying to accomplish. The machine I'm typing
>> this on has a 192.168.x.x number. The router that gave it to me also has
>> a 192.168.x.x number. However, I know that that is not the IP that the
>> world sees when my packets finally leave the building.
>
> That's the IP address the OP probably wants. At least, when I've asked
> this exact same question, that's what I meant.
>
> The only way I know of is to query an external server that will tell you.
> There's a few of them out there. Here's a few:
>
> http://checkip.dyndns.org/
> http://www.showmyip.com
> http://www.showmyip.com/simple/
> http://whatismyip.org/
>
> The basic algorithm is to connect to one of those sites and fetch the
> data it returns, then parse it appropriately. Some of them return a
> simple IP address, some a complicated bunch of text, some a nicely
> formatted XML document. Some of them only allow you to query the server a
> limited number of times. I don't remember which is which.
>
> To get you started, here's an untested piece of code:
>
> import urllib2
> import re
> data = urllib2.urlopen(site).read()
> matcher = re.compile(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
> ip_address = matcher.search(data).group()
>
>
>
> --
> Steven

Now that is a cool solution to the problem. It even works in my work
environment where I have three routers between me and the front door.

-- 
Stand Fast,
tjg.  [Timothy Grant]



More information about the Python-list mailing list