Get the public IP of user's computer
Thu 11 December 2014
Filed under Python
Here's how to get the IP
For a recent project, I needed to get the longitude and latitude of where the user was at the time. And from that data, I could get the local weather.
To do that, I'd find her local IP and then later use pygeoip.GeoIP to find the coordinates of that IP. (That's another post)
First, I used:
ip = request.remote_addr
request is part of the Flask module that i was using to create this web application. In very short, the
request 'remembers' the value of what we were requesting. Check out the request class of Flask.
Then a fellow HackerSchooler pointed out that sometimes that might get my local host (127.0.0.1) and not the IP as I thought I might get.
The suggestion was:
- First attempt to get the IP that way, since it is more 'resources efficient'.
- Also have an
ifstatement to check if it did indeed get me that local host.
- And if it is the localhost, then use
icanhazip.comto get the IP.
So here is the code:
import requests #import the request module def get_ip(): ip = request.remote_addr if ip == '127.0.0.1': ip = requests.get("http://icanhazip.com/").content return ip
ip is the response. It is the
content from the
get request to
Read more about the different attributes for requests.get(some_url).attributes http://docs.python-requests.org/en/latest/user/quickstart/#make-a-request
---MORE ABOUT REQUESTS---
requests is a more reliable library than the old urllib2