Python 2.7.3
In order to geolocate an IP address with Python you will need a database to match an IP to a location. I am using the Maxmind database, which is available for free.
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz
Next, we install the Pure Python API for Maxmind's GeoIP databases (https://github.com/appliedsec/pygeoip)
sudo pip install pygeoip
Code
import pygeoip
rawdata = pygeoip.GeoIP('/home/user/GeoLiteCity.dat')
def ipquery(ip):
data = rawdata.record_by_name(ip)
country = data['country_name']
city = data['city']
longi = data['longitude']
lat = data['latitude']
print '[x] '+str(city)+',' +str(country)
print '[x] Latitude: '+str(lat)+ ', Longitude: '+ str(longi)
Running the code
UPDATE - PYTHON 3 (Ubuntu 16.04)
sudo pip3 install pygeoip
Download Maxmind location-data
user@user:~$ cd Desktop
user@user:~/Desktop$ mkdir geolocate
user@user:~/Desktop$ cd geolocate
user@user:~/Desktop/geolocate$ wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
user@user:~/Desktop/geolocate$ gunzip GeoLiteCity.dat.gz
Code (save as geo.py in folder geolocate)
import pygeoip
rawdata = pygeoip.GeoIP('/home/user/Desktop/geolocate/GeoLiteCity.dat')
def ipquery(ip):
data = rawdata.record_by_name(ip)
country = data['country_name']
city = data['city']
longi = data['longitude']
lat = data['latitude']
print ('[x] '+str(city)+',' +str(country))
print ('[x] Latitude: '+str(lat)+ ', Longitude: '+ str(longi))
#optional
ip = input("What's your ip? ")
print (ipquery(ip))
Run the code
user@user:~/Desktop/geolocate$ python3 geo.py
What's your ip? 207.38.138.230
[x] New York,United States
[x] Latitude: 40.7449, Longitude: -73.9782