Skip to main content

How To Geolocate an IP Address with Python

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
How To Geolocate an IP with Python

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

Comments

  1. Groovy! Except for OSX I had to say:

    cd /usr/local/
    sudo curl -O http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
    sudo gunzip /usr/local/GeoLiteCity.dat.gz

    sudo pip install pygeoip

    python2.7
    import pygeoip
    rawdata = pygeoip.GeoIP('/usr/local/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)

    ip='207.38.138.230'
    ipquery(ip)

    [x] New York,United States
    [x] Latitude: 40.7143, Longitude: -74.006

    ReplyDelete
  2. Replies
    1. Just tried the code and it is still working. What problems did you have?

      Delete
  3. The benefit of this plan is that it can deal with a substantial number of addresses, in particular 4.3 billion myip info

    ReplyDelete
  4. Various IP geolocation API services are providing free geolocation information, e.g: http://ipgeolocaion.io, IPStack, IP2Location, IP-API, DB-IP, IP info, etc. Each service has different features. You can select a service according to your demand.

    Among these services, You can easily find the geolocation information of an IP address freely by using ipgeolocation.io. ipgeolocation.io provides 45000 free requests per month / 1500 per day.

    You can use it by following these simple steps:

    Just go to https://ipgeolocation.io/ and signup here.
    Then sign in and select a free plan.
    After signing in, go to the Dashboard and copy the API key.
    Use this API key to locate the IP address.
    In order to find geolocation information about an IP address, pass it as a query parameter like below. Note that apiKey is also passed as a query parameter for authorization.

    # Get geolocation for an IPv4 IP Address = 8.8.8.8

    $ curl 'https://api.ipgeolocation.io/ipg...'

    The JSON response will be as follows:

    {

    "ip": "8.8.8.8",

    "hostname": "http://google-public-dns-a.googl...",

    "continent_code": "NA",

    "continent_name": "North America",

    "country_code2": "US",

    "country_code3": "USA",

    "country_name": "United States",

    "country_capital": "Washington",

    "state_prov": "California",

    "district": "",

    "city": "Mountain View",

    "zipcode": "94043",

    "latitude": "37.4229",

    "longitude": "-122.085",

    "is_eu": false,

    "calling_code": "+1",

    "country_tld": ".us",

    "languages": "en-US,es-US,haw,fr",

    "country_flag": "


    ",

    "isp": "Level 3 Communications",

    "connection_type": "",

    "organization": "Google Inc.",

    "geoname_id": "5375480",

    "currency": {

    "code": "USD",

    "name": "US Dollar",

    "symbol": "$"

    },

    "time_zone": {

    "name": "America/Los_Angeles",

    "offset": -8,

    "current_time": "2019-01-14 03:30:00.135-0800",

    "current_time_unix": 1547465400.135,

    "is_dst": false,

    "dst_savings": 1

    }

    }

    The geolocation information for an IP address from the IP Geolocation API can be retrieved in the following languages:

    English (en)
    German (de)
    Russian (ru)
    Japanese (ja)
    French (fr)
    Chinese Simplified (cn)
    Spanish (es)
    Czech (cs)
    Italian (it)
    Disclaimer: I am working for http://ipgeolocaion.io

    ReplyDelete

Post a Comment

Popular posts from this blog

OsmocomBB - Hardware and Software Setup - Tutorial (Motorola C118)

OsmocomBB is an Open Source GSM Baseband software implementation. By using the sofware on a compatible phone (e.g. Motorola C118), you are able to make and receive phone calls, send and receive SMS, etc. based on Free Software only.       Hardware PL2303HX USB Serial To RS232 TTL Chip 2.5 mm audio jack Motorola C118 (E88) This is a typical pin-out of a 2.5 mm audio jack: L (Left Signal) Tip 1 Green R (Right Signal) Ring 2 Red GND (Ground) Sleeve 3 Bare Copper You need to soldier the 2.5mm audio jack to the USB Serial To RS232 TTL Chip, whereas TxD is at the tip of the plug RxD is at the middle contact GND is the outer contact  Software Connect the phone to your PC and check if it is being recognized. dmesg | grep tty user@user:~$ dmesg | grep tty [    0.000000] console [tty0] enabled [ 6522.143379] usb 3-2: pl2303 converter now attached to ttyUSB0 To make sure everything is working, install cu and c

Scid vs PC installation guide - Ubuntu (Mint, Debian etc.)

Scid vs PC Scid vs PC is definitely the best and most comprehensive chess software for Linux.  Unfortunately I struggled quite a bit to get it up and running. Before I start: You might prefer to watch the video. Otherwise keep on reading. Open a terminal and execute the following commands sudo apt-get install auto-apt build-essential sudo auto-apt update-local sudo auto-apt update sudo auto-apt updatedb Now make sure you got both tcl8.5-dev and tk8.5-dev installed sudo apt-get install tcl8.5-dev tcl8.5 sudo apt-get install tk8.5-dev tk8.5 Some users are reporting problems on Ubuntu 14.04. sudo apt-get install tcl8.6-dev tcl8.6 sudo apt-get install tk8.6-dev tk8.6 libgcj15-dev The 'x' refers to the current release: e.g. 4.9.tgz download scid vs pc: http://sourceforge.net/projects/scidvspc/files/source/scid_vs_pc-4.9.tgz/download tar -xzf scid_vs_pc-4.xx.tgz cd scid_vs_pc-4.x sudo auto-apt run ./configure sudo auto-apt run make sudo auto-apt run make install

Automatically Reconnect WIFI (Debian, Ubuntu etc.)

The Problem For several reason I do not have access to LAN and thus have to rely on WIFI for my mining rigs. It is fine for most of the time, but the shit hits the fan, when the connection drops for one reason or another. The Solution #!/bin/bash wlan=`/sbin/ifconfig wlan1 | grep inet\ addr | wc -l` if [ $wlan -eq 0 ]; then service network-manager restart else echo WIFI IS UP fi Note: It's either wlan0 or wlan1. Check with sudo ifconfig . Save the script and make it executable. sudo chmod +x filename.sh Now there are several ways of making sure that our script is being executed every x minutes. The easiest way of accomplishing that I think is by using the command watch . sudo su watch -n 600 sh filename.sh What it does is execute our filename.sh script every 600 seconds. Or you implement a so called cron job   sudo crontab -e Add the following PATH=/usr/sbin:/usr/bin:/sbin:/bin */5 * * * * sh /home/username/filename.sh */5 * * * * means that