Getting external IP address

Duncan Booth duncan.booth at invalid.invalid
Mon Mar 5 04:02:44 EST 2007


Steven D'Aprano <steve at REMOVEME.cybersource.com.au> wrote:

> 
>>>> from httplib import HTTPConnection
>>>> from xml.dom.ext.reader.Sax import FromXmlStream
>>>> conn = HTTPConnection('xml.showmyip.com')
>>>> conn.request('GET', '/')
>>>> doc = FromXmlStream(conn.getresponse())
>>>> print doc.getElementsByTagName('ip')[0].firstChild.data
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "/usr/lib/python2.4/UserList.py", line 28, in __getitem__
>     def __getitem__(self, i): return self.data[i]
> IndexError: list index out of range
>>>> conn.close()
> 
> I don't know how to fix it so that it works.
> 
> Can anyone help me fix that code snippet, or suggest another (better) 
way
> to get the externally visible IP address?

Try running it interactively and looking at the data you receive:

>>> conn = HTTPConnection('xml.showmyip.com')
>>> conn.request('GET', '/')

>>> resp = conn.getresponse()
>>> print resp
<httplib.HTTPResponse instance at 0x00C58350>
>>> data = resp.read()
>>> print data
<html><head><title>Object moved</title></head><body>

<h2>Object moved to <a href="http://www.showmyip.com/xml/">here</a>.
</h2>

</body></html>


If you try connecting to 'www.showmyip.com' and requesting '/xml/' it 
should work.



More information about the Python-list mailing list