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?
-
Another great website that offers a no frills solution is to get an HTTP request from icanhazip.comyurisich– yurisich2012-01-13 12:32:15 +00:00Commented Jan 13, 2012 at 12:32
Add a comment
|
9 Answers
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.
2 Comments
Matthew Schinckel
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.
jfs
@MatthewSchinckel: +1 for mentioning another NAT. Also, different external services may see different external IPs e.g., I remember that to access a library site, I had to use a different route so that the site sees different (allowed) ip i.e., the public ip may depend on destination.
https://github.com/bobeirasa/mini-scripts/blob/master/externalip.py
'''
Finds your external IP address
'''
import urllib
import re
def get_ip():
group = re.compile(u'(?P<ip>\d+\.\d+\.\d+\.\d+)').search(urllib.URLopener().open('http://jsonip.com/').read()).groupdict()
return group['ip']
if __name__ == '__main__':
print get_ip()
2 Comments
chacmool
Was not aware of jsonip.com--thanks. Here's a little more "jsonic" variation of your answer (auto formatting is messing up the url): json.loads(urllib2.urlopen(urllib2.Request('jsonip.com', headers = {'Content-Type': 'application/json'})).read())['ip']
Youssef
@Rafael Lopes The link was moved to
https://jsonip.com/ (301 permanently). Btw. for me it works perfectly. In my case, the external IP in the response is in IPv6 format, which is fine. Nice one.You'll need to use an external system to do this.
DuckDuckGo's IP answer will give you exactly what you want, and in JSON!
import requests
def detect_public_ip():
try:
# Use a get request for api.duckduckgo.com
raw = requests.get('https://api.duckduckgo.com/?q=ip&format=json')
# load the request as json, look for Answer.
# split on spaces, find the 5th index ( as it starts at 0 ), which is the IP address
answer = raw.json()["Answer"].split()[4]
# if there are any connection issues, error out
except Exception as e:
return 'Error: {0}'.format(e)
# otherwise, return answer
else:
return answer
public_ip = detect_public_ip()
print(public_ip)
Comments
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]
1 Comment
Claudiu
note they say to not do this more than once every 300 seconds