Switch to full style
Python Technology Tutorials Written By Members.
Post a reply

how to use GeoIP with Python

Sat Jul 28, 2012 4:27 pm

You may need to use GeoIP software for IP address geo location finding as free or paid service; GeoIP databases provide information until the Country/City level, the Maxmind’s GeoIP is a famous service for IP address geographic information among developers, there is API for Python language you can find it here:
Code:
https://github.com/appliedsec/pygeoip

This is a C Python library from Maxmind and you will need to run the following codes, now how to run the code? For sure we will import the GeoIP and we will use its API , following snippet we are trying to get city and country information:
Code:

import GeoIP

## creating an object
myGeoIP = GeoIP.new(GeoIP.GEOIP_STANDARD)

 
print myGeoIP
.country_code_by_addr("193.45.25.158")
print myGeoIP.country_code_by_name("codemiles.com")

 
## Using GeoIP Memory Cache
myGeoIP = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE | GeoIP.GEOIP_CHECK_CACHE)
 
print geo
.country_code_by_addr("173.15.27.167")
print geo.country_code_by_name("codemiles.com")

## using the City database
myGeoIP=GeoIP.open("/usr/local/share/GeoIP/GeoIPCity.dat",GeoIP.GEOIP_STANDARD)

print "Using GeoIP City database"
geoRecord = geo.record_by_addr("173.15.27.167")

if geoRecord!= None:
    print geoRecord ['country_code']
    print geoRecord ['country_name']
    print geoRecord ['time_zone']
    print 
geoRecord ['city']
    print 
geoRecord ['region']
    print 
geoRecord ['region_name']
    print 
geoRecord ['postal_code']
    print 
geoRecord ['latitude']
    print 
geoRecord ['longitude']
    print 
geoRecord ['area_code']
 


You may wondering about this line :
Code:

myGeoIP 
= GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE | GeoIP.GEOIP_CHECK_CACHE)
 

We used two flags: .GEOIP_MEMORY_CACHE | GeoIP.GEOIP_CHECK_CACHE
GEOIP_MEMORY_CACHE: increases the performance but for sure needs more memory caching
GEOIP_CHECK_CACHE: a reload of the GEO database if the database file is modified



Post a reply
  Related Posts  to : how to use GeoIP with Python
 hashing in python     -  
 Reading email in Python     -  
 Python Module for MySQL     -  
 How to read and write to CSV file from python     -  
 exception handling try and catch in Python     -  
 usage of SQLite database from Python     -  
 Python Training from Certified Experts (ap2v.com)     -  
 Build Linear Regression in Python - Supervised Learning     -  

Topic Tags

Python GEO