Python API Tutorials

Build an IP Scanner Tool in Python with geoPlugin IP Geolocation API

Network administrators are always worried about those unscrupulous intruders who try to sneak into their networks with malicious intentions. With the mass-scale deployment of IoT devices, cybersecurity is getting more challenging day by day, with hackers employing unique ways to scale up their brute force attacks on popular Internet websites. Although there are umpteen products available for managing network and website security, nothing beats a custom tool that gets the job done for auditing your network traffic. In case you need such a tool that can scan a list of suspicious IP addresses to find more information about them, the geoPlugin IP Geolocation API is your best buddy.

In this blog post, we are going to show you how to leverage the geoPlugin IP Geolocation API to build an IP scanning utility script using Python.  In case you are unaware, IP addresses are allotted to Internet Service Providers operating in a given region in the world. Hence, it is possible to track a user’s location by finding out his/her IP address and then tracing it back to the city or country of origin where the IP address was allotted to the user’s ISP.

Related: How to use IP Geolocation with JavaScript

What is IP Geolocation?

Geolocation is the identification or designation of the geographic location of an item, such as a mobile phone, radar source, or internet-connected computer. In that sense, IP Geolocation can be defined as the technique used to map a particular IP address to a geographic location from where the device is connecting to the internet.

Learn more here.

What is the Best IP Geolocation API?

Some of the best IP Geolocation APIs include:

  • Telize – Offers JSON IP and GeoIP services. Supports both cross-origin resource sharing (CORS) and JSONP.
  • Apilitiy.io – This API returns geolocation of any IP address with relevant information like continent, country, region, city, and more.
  • geoPlugin – IP Geolocation service available in multiple programming languages (we’ll be using this one today).
  • IPWHOIS.io – Filter out bot traffic, customize content (based on the user’s location), and more.
  • Ipregistry – Fast and reliable IP geolocation and threat data API.

See the full list here.

What is the geoPlugin API

The geoPlugin API offers the services of IP geolocation as well as currency conversion, via two separate endpoint categories. 

 

It’s IP geolocation service is unique in a way that it returns the API response in several formats, including embeddable programming language formats

Here is a typical JSON response that you get from the API response for an IP address.

{
"geoplugin_request":"202.44.76.8",
"geoplugin_status":200,
"geoplugin_delay":"1ms",
"geoplugin_credit":"Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.",
"geoplugin_city":"Melbourne",
"geoplugin_region":"Victoria",
"geoplugin_regionCode":"VIC",
"geoplugin_regionName":"Victoria",
"geoplugin_areaCode":"",
"geoplugin_dmaCode":"",
"geoplugin_countryCode":"AU",
"geoplugin_countryName":"Australia",
"geoplugin_inEU":0,
"geoplugin_euVATrate":false,
"geoplugin_continentCode":"OC",
"geoplugin_continentName":"Oceania",
"geoplugin_latitude":"-37.8103",
"geoplugin_longitude":"144.9544",
"geoplugin_locationAccuracyRadius":"1000",
"geoplugin_timezone":"Australia/Melbourne"
}

If you, as a network administrator, are wondering about the origin of specific suspicious IP addresses, then you are not alone. But instead of pondering over them, you can code up a Python script in no time, which will prepare a report with geolocation details about all the IPs.

All you need is the IP scanning script. Let’s build it with the geoPlugin IP Geolocation API.  

 

Getting Access to the IP Geolocation API

1. Sign Up for a RapidAPI User Account

To begin using the geoPlugin API, you’ll first need to sign up for a free RapidAPI developer account.

RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.

2. Navigate to the geoPlugin API Page

Search for “geoPlugin” in the search bar, or click here to go to the API console directly.

3. Subscribe to the geoPlugin IP Geolocation API

The geoPlugin API gives you 100k free API requests per day under the basic subscription. Subscribe to the Basic plan and you are all set to leverage this API.

Note: The Basic plan does not provide access to the currency conversion API endpoints. That is part of the paid plains and is out of scope for this post.

 

How To Use IP Geolocation API with Python to find Locations

You will now learn how to use this API with Python. Head over to the API console and choose the “JSON IP Geolocation” endpoint. 

If you specify a value for the ‘íp’ parameter, the API finds the details of it. Otherwise, it returns the details of the IP from which the API call is requested. 

Enter an arbitrary IP address and open the “Code Snippet” tab for Python > Requests.

The code snippet shown on the right is for invoking the API using the Python Requests library. Requests is a popular Python library for handling HTTP calls.   

You will use this snippet in the next section, where you are going to build the IP scanning script using Python. 

 

How to Build an IP Scanning Tool with the IP Geolocation API

Before you start coding, you need to set up your development environment and install a few dependencies. 

Since the script is in Python and uses the Requests library, you need to have the following prerequisites in place.

Prerequisites

  1. Python 3 Runtime Environment: – You must have the Python 3 runtime environment installed on your computer. Download the latest Python 3 release from the official download page and make sure that you choose the right package as per your operating system.

      2. Python Requests – You can check out the official Requests documentation here.

The Requests package can be installed using the Pip utility.

pip install requests

In case you want to set up a virtual environment, then you can follow this official link to get a virtual lightweight python runtime. 

Now it’s a good idea to fire up your favorite Python code editor and create a new file. So follow the step by step instructions below to build the code for IP scanner.

1. Import the Libraries

First up, you need to import the python modules that are used in the script.

Here is the list of all imports

import sys
import json
import requests
import csv

You will understand the significance of each of the imported modules in the later steps. For now, let’s just move onto the next step.

 

2. Initialize the Global Data

For this script, the only global data that we need is the variable declaration for RapidAPI subscription key. 

RAPIDAPI_KEY  = “<YOUR_RAPIDAPI_KEY>”

You must replace the <YOUR_RAPIDAPI_KEY> with your actual subscription key that you received upon subscribing to RapidAPI account.

 

3. Define a function to call the geoPlugin IP Geolocation API

You need to define a separate function to call the geoPlugin API. This is where you can take a cue from the Python code snippet we saw earlier to write the code for the function.

def trigger_api(ip):

  querystring = {"ip": ip}

  headers = {
         'x-rapidapi-host': "geoplugin.p.rapidapi.com",
         'x-rapidapi-key': RAPIDAPI_KEY
        }

  url = "https://geoplugin.p.rapidapi.com/ip/json.gp"

  response = requests.request("GET", url, headers=headers, params=querystring)

  if(200 == response.status_code):
    return json.loads(response.text)
  else:
    return None

The trigger_api( ) is a function that is passed with an argument containing the IP address as string. It calls the geoPlugin API’s “JSON IP Geolocation” endpoint and returns the output as a Python dictionary.

3. Define the main login of the script

The main function of this script does two things. It reads an input file containing a list of IP addresses in CSV format. Additionally, it also opens another CSV file for capturing the location details, which is the output file.

if __name__ == "__main__":

  try: 

    print("Scanning list of IPs ")

    with open('ip-list.csv', 'r',newline='') as input_file:

      with open('ip-list-updated.csv', 'w',newline='') as output_file:

To keep things simple, we assume that the input file is named ‘ip-list.csv’, and it is placed in the same path as the Python script.  The output file name is ‘íp-list-updated.csv’. The script generates this output file upon execution. 

 

4 Invoke the API and capture geolocation data

Now you are getting into the meat of the logic. With both the files open, you can start reading the IP addresses, one by one and invoke the API to capture the geolocation data.  

Add the following code inside the second with block shown in the previous step that opens the output file.

ip_reader = csv.reader(input_file, delimiter=' ')
        
ip_writer = csv.writer(output_file)

for row in ip_reader:
          
  current_ip = row[0]

  print("Getting details for IP: " + current_ip)

  api_response = trigger_api(current_ip)

  ip_city     = api_response["geoplugin_city"] if api_response["geoplugin_city"] != '' else api_response["geoplugin_region"] 
  ip_country  = api_response["geoplugin_countryName"]
  ip_latitude = api_response["geoplugin_latitude"]
  ip_longitude = api_response["geoplugin_longitude"]

  ip_writer.writerow([current_ip,ip_city,ip_country,ip_latitude,ip_longitude])

A lot is happening here. First, you iterate over the contents of the input file to read each IP address. Then you call the trigger_api( ) function to retrieve the entire geolocation details of that IP address. Finally, you extract the city, region, country along with the latitude and longitude for that IP and write it to the output file as one record. 

That’s it!

We are done with the code. Here is the complete IP scanning script with additional cleanup for files and exception handling.

import sys
import json
import requests
import csv


RAPIDAPI_KEY  = "<YOUR_RAPIDAPI_KEY>"

def trigger_api(ip):

  querystring = {"ip": ip}

  headers = {
     'x-rapidapi-host': "geoplugin.p.rapidapi.com",
     'x-rapidapi-key': RAPIDAPI_KEY
    }

  url = "https://geoplugin.p.rapidapi.com/ip/json.gp"

  response = requests.request("GET", url, headers=headers, params=querystring)

  if(200 == response.status_code):
    return json.loads(response.text)
  else:
    return None

if __name__ == "__main__":

  try: 

    print("Scanning list of IPs ")

    with open('ip-list.csv', 'r',newline='') as input_file:

      with open('ip-list-updated.csv', 'w',newline='') as output_file:

        ip_reader = csv.reader(input_file, delimiter=' ')
        
        ip_writer = csv.writer(output_file)

        for row in ip_reader:
          
          current_ip = row[0]

          print("Getting details for IP: " + current_ip)

          api_response = trigger_api(current_ip)

          ip_city     = api_response["geoplugin_city"] if api_response["geoplugin_city"] != '' else api_response["geoplugin_region"] 
          ip_country  = api_response["geoplugin_countryName"]
          ip_latitude = api_response["geoplugin_latitude"]
          ip_longitude = api_response["geoplugin_longitude"]

          ip_writer.writerow([current_ip,ip_city,ip_country,ip_latitude,ip_longitude]) 

        output_file.close()

      input_file.close()
  

  except TypeError as e:

    print(e)
    print("Type Error...Aborting")
              
  except csv.Error as e:
              
    print(e)
    print("CSV Error...Aborting")
            
  except Exception as e:

    print("Major Exception ...Aborting")
    sys.exit(e)

Make sure you take care of the indentations and update the key. Save the file as get_ip_details.py 

 

Testing the IP Scanner Tool

Now is the time for the rubber to meet the road. 

To test this script, you need an input file containing a list of IP addresses. Here is a sample content of the input file.

Since this is a CSV file you must save it with the .csv extension. Also, make sure that the file is located at the same path where you saved the Python script.

 

With the input file prepared, it’s time to trigger the script with the Python interpreter. 

python get_ip_details.py

And here is how the generated output file looks like.

 

Now you know the locations where those IP addresses originated from. 

 

Take Charge Of Your Network Security

The geoPlugin IP Geolocation API is very generous in granting 100k free API calls per day. This means that you can scan a hundred thousand IP addresses every day. This limit is enough for most websites and online properties.  

So it’s time for you to take a closer look at your Internet traffic with the help of geoPlugin IP Geolocation API. As a next level enhancement to this IP scanner tool, you can plot the IP geolocation on a map and get a better view of your traffic from around the world.       

Related: Build a Geolocation Backend with Node/Express

 

5/5 - (1 vote)

View Comments

  • hi sir i got this error"TypeError: 'NoneType' object is not subscriptable" mind to shed light for us regarding this matter itd be a huge help cause ive working on it but nothing fixed.thank you for your time

  • Excellent resources, thank you. You can also review these sources on Data Hunters as they do for eXtReME IP LookUP (however it's spelled; our Fraud Department uses it all the time and we share space with them).

  • thank you sir for this article, don't forgot add this website ip-geo.ru give access to your ip or any ip you get a full information about this ip like location latitude country by ip state by ip and you can see if ip blocked or not ip bots scanner give you a score about this ip if a robot or a spider or a bot or is a real ip

Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

2 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

3 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

1 month ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago