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.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 ( 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 if statement to check if it did indeed get me that local host.
  • And if it is the localhost, then use to get the IP.

So here is the code:

import requests  #import the request module

def get_ip():
    ip = request.remote_addr
    if ip == '':
        ip = requests.get("").content
    return ip

requests.get: the 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


requests is a more reliable library than the old urllib2

Comments © Dee Kras Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More