How to find location with IP address in Python?

I am developing a project, that needs to store user location in my data base. I got the public IP address of that user. But I am unable to get the user location. I have tried several ways (from StackOverflow) but I didn't find any hint. Like the below

url = urllib.urlopen("http://api.hostip.info/get_html.php?ip=%s&position=true" % ip)
data = re.compile('^[^\(]+\(|\)$').sub('', url.read())
print data

but I am getting the result as

Unknown Country?) (XX)
City: (Unknown City?)

another way:

import urllib

response = urllib.urlopen("http://api.hostip.info/get_html.php?ip={}&position=true".format(ip)).read()

print(response)

but the result is

Country: (Unknown Country?) (XX)
City: (Unknown City?)

Latitude: 
Longitude: 
IP: 115.xxx.xxx.xx

Any help would be appreciated!


One of the simplest methods for getting the IP address as well as the location in detail is to use http://ipinfo.io

import re
import json
from urllib2 import urlopen

url = 'http://ipinfo.io/json'
response = urlopen(url)
data = json.load(response)

IP=data['ip']
org=data['org']
city = data['city']
country=data['country']
region=data['region']

print 'Your IP detail\n '
print 'IP : {4} \nRegion : {1} \nCountry : {2} \nCity : {3} \nOrg : {0}'.format(org,region,country,city,IP)

Try with pygeoip

~$ ping stackoverflow.com
PING stackoverflow.com (198.252.206.16) 56(84) bytes of data.

>>> import pygeoip
>>> GEOIP = pygeoip.GeoIP("/absolute_path/GeoIP.dat", pygeoip.MEMORY_CACHE)
>>> GEOIP.country_name_by_addr(ip)
'United States'

GeoIP.data is available here


for python-3.x

def ipInfo(addr=''):
    from urllib.request import urlopen
    from json import load
    if addr == '':
        url = 'https://ipinfo.io/json'
    else:
        url = 'https://ipinfo.io/' + addr + '/json'
    res = urlopen(url)
    #response from url(if res==None then check connection)
    data = load(res)
    #will load the json response into data
    for attr in data.keys():
        #will print the data line by line
        print(attr,' '*13+'\t->\t',data[attr])

Thanks for all the solutions and workarounds! However, I was not able to use all of the above methods.

Here is what worked for me:

import requests

response = requests.get("https://geolocation-db.com/json/39.110.142.79&position=true").json()

This method seemed simple and easy to use. (I needed to work with a dictionary response...)

In the future, the "geolocation-db.com" might become unavailable, so alternative sources might be required!


Assuming that you got the ip address already, you can try to use the IP2Location Python Library to get the user location. A sample code is like this:

import os
import IP2Location

database = IP2Location.IP2Location(os.path.join("data", "IPV4-COUNTRY.BIN"))

rec = database.get_all(ip)

print(rec.country_short)
print(rec.country_long)
print(rec.region)
print(rec.city)
print(rec.isp)  
print(rec.latitude)
print(rec.longitude)            
print(rec.domain)
print(rec.zipcode)
print(rec.timezone)
print(rec.netspeed)
print(rec.idd_code)
print(rec.area_code)
print(rec.weather_code)
print(rec.weather_name)
print(rec.mcc)
print(rec.mnc)
print(rec.mobile_brand)
print(rec.elevation)
print(rec.usage_type)

Depends on your requirement, for example if you want to get the user's country name and region name, you can do this:

import os
import IP2Location

database = IP2Location.IP2Location(os.path.join("data", "IPV4-COUNTRY.BIN"))

rec = database.get_all(ip)

user_country = rec.country_long
user_region = rec.region

For more details, you can visit here: IP2Location Python library

Github link: IP2Location Python library Github