Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the country and city of a user accessing your site?

How can you detect the country of origin of the users accessing your site?

I'm using Google Analytics on my site and can see that I have users coming from different regions of the world.

But within my application I would like to provide some additional customization based on the country and perhaps the city.

Is it possible to detect this infomation from the browser? This is a Python web application.

like image 256
Don King Avatar asked Jul 22 '09 05:07

Don King


3 Answers

Grab and gunzip http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz, install the GeoIP-Python package (python-geoip package if you're in Debian or Ubuntu, otherwise install http://geolite.maxmind.com/download/geoip/api/python/GeoIP-Python-1.2.4.tar.gz), and do:

import GeoIP
gi = GeoIP.open("GeoLiteCity.dat", GeoIP.GEOIP_INDEX_CACHE | GeoIP.GEOIP_CHECK_CACHE)
print gi.record_by_name("74.125.67.100") # a www.google.com IP

{'city': 'Mountain View', 'region_name': 'California', 'region': 'CA', 'area_code': 650, 'time_zone': 'America/Los_Angeles', 'longitude': -122.05740356445312, 'country_code3': 'USA', 'latitude': 37.419200897216797, 'postal_code': '94043', 'dma_code': 807, 'country_code': 'US', 'country_name': 'United States'}

The database is free (http://geolite.maxmind.com/download/geoip/database/LICENSE.txt). They do sell it, too; I think that just gets you more frequent updates.

like image 88
Glenn Maynard Avatar answered Sep 30 '22 00:09

Glenn Maynard


Get the visitor's IP and check it with a geolocation web service (or purchase a geolocation database if you're keen to host that determination in-house).

like image 40
Alex Martelli Avatar answered Sep 30 '22 00:09

Alex Martelli


Max mind costs money. For a free yet country code only solution you can try: https://pypi.python.org/pypi/geoip2nation/

pip install geoip2nation

from geoip import geoip
r = geoip.GeoIp()
r.load_memory()
r.resolve("12.12.12.12").country_code
#This prints : 'US'

print r.resolve("123.44.57.4")
#This prints : {'country': 'Korea (South)', 'host_name': '', 'country_code': 'KR'}

r.resolve2("12.12.12.12")
#This prints : 'US'
like image 43
Mitzi Avatar answered Sep 30 '22 00:09

Mitzi