473,608 Members | 2,083 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting external IP address

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

If I do this:
>>import socket
socket.gethos tbyname(socket. gethostname())
'127.0.0.1'
>>socket.gethos tbyname_ex(sock et.gethostname( ))
('localhost.loc aldomain', ['localhost'], ['127.0.0.1'])

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.pytho n a few years ago:

http://mail.python.org/pipermail/pyt...ch/192495.html

which seems like it _should_ do what I want, but it doesn't: I get an
exception.
>>from httplib import HTTPConnection
from xml.dom.ext.rea der.Sax import FromXmlStream
conn = HTTPConnection( 'xml.showmyip.c om')
conn.request( 'GET', '/')
doc = FromXmlStream(c onn.getresponse ())
print doc.getElements ByTagName('ip')[0].firstChild.dat a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/UserList.py", line 28, in __getitem__
def __getitem__(sel f, 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?
--
Steven D'Aprano

Mar 5 '07 #1
8 4159
Steven D'Aprano <st***@REMOVEME .cybersource.co m.auwrote:
>
>>>from httplib import HTTPConnection
from xml.dom.ext.rea der.Sax import FromXmlStream
conn = HTTPConnection( 'xml.showmyip.c om')
conn.request ('GET', '/')
doc = FromXmlStream(c onn.getresponse ())
print doc.getElements ByTagName('ip')[0].firstChild.dat a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/UserList.py", line 28, in __getitem__
def __getitem__(sel f, 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.c om')
conn.request( 'GET', '/')
>>resp = conn.getrespons e()
print resp
<httplib.HTTPRe sponse instance at 0x00C58350>
>>data = resp.read()
print data
<html><head><ti tle>Object moved</title></head><body>

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

</body></html>
If you try connecting to 'www.showmyip.c om' and requesting '/xml/' it
should work.
Mar 5 '07 #2
Duncan Booth <du**********@i nvalid.invalidw rites:
If you try connecting to 'www.showmyip.c om' and requesting '/xml/' it
should work.
If the firewall is really obnoxious, it can bounce consecutive queries
around between multiple originating IP addresses. That is uncommon
but it's been done from time to time.
Mar 5 '07 #3
Paul Rubin <http://ph****@NOSPAM.i nvalidwrote:
Duncan Booth <du**********@i nvalid.invalidw rites:
>If you try connecting to 'www.showmyip.c om' and requesting '/xml/' it
should work.

If the firewall is really obnoxious, it can bounce consecutive queries
around between multiple originating IP addresses. That is uncommon
but it's been done from time to time.
Yes, each connection through the firewall needs to have a unique
originating ip and port number. If there are too many machines inside the
firewall then you may need to allocate multiple ip addresses on the
outside. I would hope that in general a single internal IP should map to
one external IP at a time (otherwise you would have problems with ip based
session persistence connecting to load balanced systems), but you might
expect to bounce round different IPs after periods of inactivity.

Also you could have multiple levels of NAT in which case the question
becomes whether Steven wants the IP as seen from outside the immediate
firewall or outside the final one. Maybe he should be using IPv6 to avoid
all this?
Mar 5 '07 #4
On Mon, 05 Mar 2007 09:02:44 +0000, Duncan Booth wrote:
Try running it interactively and looking at the data you receive:
>>>conn = HTTPConnection( 'xml.showmyip.c om')
conn.request ('GET', '/')
>>>resp = conn.getrespons e()
print resp
<httplib.HTTPRe sponse instance at 0x00C58350>
>>>data = resp.read()
print data
<html><head><ti tle>Object moved</title></head><body>

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

</body></html>
Ah! That's the clue I needed -- thanks.
If you try connecting to 'www.showmyip.c om' and requesting '/xml/' it
should work.
Thank you muchly! That seems to do the trick.
--
Steven.

Mar 6 '07 #5
Steven D'Aprano <st***@REMOVEME .cybersource.co m.auwrote:
>I have a PC behind a firewall, and I'm trying to programmaticall y
determine the IP address visible from outside the firewall.
[ ... ]
Can anyone help me fix that code snippet, or suggest another (better) way
to get the externally visible IP address?
Depending on your circumstances, it may be possible to just ask the
firewall. You'll probably need some kind of administrator login, and
may well have to parse HTML if it's only got a web interface, but it
does mean that you don't have to connect to anything in the outside
world.

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Mar 6 '07 #6
I have a PC behind a firewall, and I'm trying to programmaticall y
determine the IP address visible from outside the firewall.
....
Steven ....

Following is another alternative that might at least
be worth consideration ....

I use the lynx command shown as a command-line alias
under Debian linux ....
>>>
import os

pipe_in = os.popen( 'lynx --dump http://checkip.dyndns. org' )

ip_addr = pipe_in.readlin es()

for this in ip_addr :
.... print this
....
Current IP Address: 65.39.92.38
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Mar 6 '07 #7
The above suggestions seem nice, but I find this one easier:

import urllib2
ext_ip = urllib2.urlopen ('http://whatismyip.org/').read()
print ext_ip

The nice thing about the above code is that http://whatismyip.org/
only contains exactly what you want (the ip, nothing more, nothing
less), so no parsing is necessary

Best,
Sergio

On 3/6/07, Cousin Stanley <co***********@ hotmail.comwrot e:
>
I have a PC behind a firewall, and I'm trying to programmaticall y
determine the IP address visible from outside the firewall.
....

Steven ....

Following is another alternative that might at least
be worth consideration ....

I use the lynx command shown as a command-line alias
under Debian linux ....
>>
import os

pipe_in = os.popen( 'lynx --dump http://checkip.dyndns. org' )

ip_addr = pipe_in.readlin es()

for this in ip_addr :
... print this
...
Current IP Address: 65.39.92.38
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
--
http://mail.python.org/mailman/listinfo/python-list
Mar 6 '07 #8
On Tue, 06 Mar 2007 14:40:37 -0500, Sergio Correia wrote:
The above suggestions seem nice, but I find this one easier:
[snip]
Thanks to everybody who replied, that's great.
--
Steven.

Mar 6 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3016
by: N. Graves | last post by:
I'm planning to develop a process to import data from an external flat file to a new table automatically. As usual I'm having a hard time getting started on the solution because of the Access's flexibility. Please help me with your suggestion's about the best way accomplish this or do you know of any examples that I could review or download. Thanks in advance! Norris
1
2276
by: | last post by:
I'm trying to get (or set) the focus on an external window but to no avail. I've imported the "GetActiveWindow" and "GetFocus" from the user32.dll but those 2 functions seem to only work for windows my application owns... I can get the hWnd of the process I want to check/set focus on. Any help would be greatly appresated. Just to be a little more clear, say NotePad is up; I'm trying to make my program set focus to the opened Notepad...
4
7289
by: Macca | last post by:
Hi, I am using an asynchronous socket server to allow comms between multiple clients and my server. I know how to obtain the IPAddress of the client (network device) as shown below :- string sensorIPAddress = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString(); but what I would like to obtain is the physical/MACID of the client.
4
2512
by: iwdu15 | last post by:
Hi, im using this code to get a computers IPAddress Net.Dns.GetHostEntry(Net.Dns.GetHostName()).AddressList(0) but that only gets the Lan IPAddress....how can i get the internet IP address? -- -iwdu15
1
2317
by: rahulbsbs | last post by:
Sir how can i get the ip address of the remote system by writting a java code,ie i want to get ip address of the remote system that is connected to my server computer ,the ip address must be obtained by writting a java program.Is there any class for that.Please give me an example for getting this.
0
1519
kaleeswaran
by: kaleeswaran | last post by:
hi! currently i am doing registration form... i like to getting an ip address from the respective system i mean where the user using my application form, the respective system ip address will be dispalyed after completion of my registration form.. so what should i do to get an ip address.... i am using jsp .... hope i am get a quick replay from you, thank you,
0
1161
kaleeswaran
by: kaleeswaran | last post by:
hi!!! i was getting ip address of my local machine in my network using jsp. can i get all of my local machine address which is connected in the network...? if so give me some idea about that.................. thanks, kalees
5
1219
by: Gangreen | last post by:
I have a server , and i want to get the external ip of the clients who connect to me. How can I do this? thx (I do not want to use whatismyip's automation page)
0
8478
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8152
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8341
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5476
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3962
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4025
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1598
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1331
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.