Getting external IP address

Steven D'Aprano steve at
Mon Mar 5 09:49:58 CET 2007

I have a PC behind a firewall, and I'm trying to programmatically
determine the IP address visible from outside the firewall.

If I do this:

>>> import socket
>>> socket.gethostbyname(socket.gethostname())
>>> socket.gethostbyname_ex(socket.gethostname())
('localhost.localdomain', ['localhost'], [''])

I get my internal IP address, which is not what I want.

Other tricks, like parsing the output of os.system('/sbin/ifconfig eth0')
also give me my internal IP address.

I found this post on comp.lang.python a few years ago:

which seems like it _should_ do what I want, but it doesn't: I get an

>>> from httplib import HTTPConnection
>>> from xml.dom.ext.reader.Sax import FromXmlStream
>>> conn = HTTPConnection('')
>>> conn.request('GET', '/')
>>> doc = FromXmlStream(conn.getresponse())
>>> print doc.getElementsByTagName('ip')[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.4/", line 28, in __getitem__
    def __getitem__(self, i): return[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?

Steven D'Aprano 

More information about the Python-list mailing list