tags:

views:

1492

answers:

4

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?

+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
+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
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
+1  A: 

hi

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(("msn.com",80))

s.getsockname()

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