When I call socket.getsockname()
on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?
views:
1492answers:
4
+5
A:
This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.
John Millikin
2008-09-12 04:23:53
+2
A:
The only way I can think of that's guaranteed to give it to you is to hit a service like http://whatismyip.com/ to get it.
Cody Brocious
2008-09-12 04:24:34
Not quite sure why this was voted down. This is IMHO the only way to get the external IP address of any system. Just because a router tells you what it thinks your IP address is, or what it thinks it's IP address is doesn't mean there isn't another NAT in place.
Matthew Schinckel
2008-09-12 07:50:00
A:
Using the address suggested in the source of http://whatismyip.com
import urllib
def get_my_ip_address():
whatismyip = 'http://www.whatismyip.com/automation/n09230945.asp'
return urllib.urlopen(whatismyip).readlines()[0]
frankjania
2010-04-15 14:46:48