Denizhalil

Building Your Own IP Address Information Tool with Python

Introduction

In today’s interconnected world, understanding IP addresses and their related information is crucial. Whether you’re a network administrator, cybersecurity enthusiast, or just a curious individual, having a tool to fetch IP address details can be incredibly useful. In this article, we’ll explore how to build a Python-based tool to retrieve information about an IP address, including location, ISP, and more.

Learning Objectives

By the end of this article, you will:

  • Understand what an IP address is and its significance.
  • Learn how to use Python to create a tool that fetches detailed IP address information.
  • Gain experience with API requests and handling JSON data in Python.
  • Develop skills in organizing code with classes and functions for better maintainability.

What is an IP Address?

An IP address (Internet Protocol address) is a unique identifier assigned to each device connected to a network that uses the Internet Protocol for communication. It serves two main purposes: host or network interface identification and location addressing. IP addresses come in two versions: IPv4 and IPv6. An IPv4 address is a 32-bit number, typically represented in dot-decimal notation (e.g., 192.168.1.1), while an IPv6 address is a 128-bit number, represented in hexadecimal format.

IP addresses are critical for routing information across the internet, ensuring data packets reach their intended destinations. They also provide information about the geographic location of the device, the Internet Service Provider (ISP), and other network details.

What is an IP Address?

An IP address (Internet Protocol address) is a unique identifier assigned to each device connected to a network that uses the Internet Protocol for communication. It serves two main purposes: host or network interface identification and location addressing. IP addresses come in two versions: IPv4 and IPv6. An IPv4 address is a 32-bit number, typically represented in dot-decimal notation (e.g., 192.168.1.1), while an IPv6 address is a 128-bit number, represented in hexadecimal format.

IP addresses are critical for routing information across the internet, ensuring data packets reach their intended destinations. They also provide information about the geographic location of the device, the Internet Service Provider (ISP), and other network details.

Amazon Product
Programming Symbols Stickers

Editor’s Recommendation

Mastering Python Networking – Fourth Edition: Utilize Python packages and frameworks for network automation, monitoring, cloud, and management 4th ed. Edition

-10% $48.59 on Amazon

Building Our IP Information Tool with Python

Let’s dive into creating a Python tool that retrieves IP address information using an external API.

Step 1: Setting Up the Environment

First, ensure you have Python installed on your machine. You’ll also need the requests library to handle HTTP requests. You can install it using pip:

pip install requests
Step 2: Writing the Python Script

We’ll organize our script using a class to encapsulate the functionality. This approach makes the code cleaner and more maintainable. Let’s break down the code step by step:

Importing the Required Library
import requests

We import the requests library, which allows us to send HTTP requests easily. We’ll use this library to make requests to the IP information API.

Defining the IPInfoFetcher Class
class IPInfoFetcher:
    def __init__(self):
        self.api_url = 'https://ipinfo.io/'

We define a class IPInfoFetcher. The __init__ method initializes the class with the base URL for the ipinfo.io API. This URL will be used to fetch IP address information.

The get_ip_info Method
def get_ip_info(self, ip=None):
        url = self.api_url
        if ip:
            url += ip
        url += '/json'
        try:
            response = requests.get(url)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            print("Failed to retrieve IP information:", e)
            return None
  • Constructing the URL: The get_ip_info method constructs the full API URL. If an IP address is provided as an argument, it appends this IP address to the base URL. Otherwise, it constructs the URL to get the information about the current IP address.
  • Sending the Request: It sends a GET request to the constructed URL using requests.get(url).
  • Handling Errors: It uses raise_for_status() to check if the request was successful. If there’s an error, it catches the exception and prints an error message, returning None.
  • Returning the Response: If the request is successful, it returns the JSON response containing the IP information.
The display_ip_info Method
def display_ip_info(self, ip_info):
        if ip_info:
            print(f"IP Address: {ip_info.get('ip')}")
            print(f"City: {ip_info.get('city')}")
            print(f"Region: {ip_info.get('region')}")
            print(f"Country: {ip_info.get('country')}")
            print(f"Location: {ip_info.get('loc')}")
            print(f"ISP: {ip_info.get('org')}")
  • Displaying the Information: The display_ip_info method takes the IP information dictionary as an argument and prints out the relevant details such as IP address, city, region, country, location, and ISP.
The main Function
def main():
    fetcher = IPInfoFetcher()
    
    choice = input("Do you want to get your own IP information (own) or query an IP address (ip)? ").strip().lower()

    if choice == 'own':
        ip_info = fetcher.get_ip_info()
    elif choice == 'ip':
        ip = input("Please enter the IP address you want to query: ").strip()
        ip_info = fetcher.get_ip_info(ip)
    else:
        print("Invalid choice!")
        ip_info = None

    fetcher.display_ip_info(ip_info)
  • Creating an Instance: The main function creates an instance of the IPInfoFetcher class.
  • User Interaction: It prompts the user to choose whether they want to get their own IP information or query a specific IP address.
  • Fetching IP Information: Based on the user’s choice, it calls the appropriate method to get the IP information.
  • Displaying the Information: It then calls display_ip_info to print the fetched IP information.
Running the Script
if __name__ == "__main__":
    main()

This block ensures that the main function runs only if the script is executed directly, not when it is imported as a module.

Amazon Product
Programming Symbols Stickers

Editor’s Recommendation

The Big Book of Small Python Projects: 81 Easy Practice Programs

$26.78 on Amazon

Step 3: Running the Script

To run the script, simply execute it using Python:

python3 ip_info_tool.py

You will be prompted to choose whether you want to get information about your own IP address or query a specific IP address. Enter your choice, and the tool will display the relevant information.

Conclusion

By following this guide, you’ve built a useful Python tool to retrieve and display IP address information. This tool leverages the ipinfo.io API to provide detailed information, including the city, region, country, location, and ISP of the IP address. This project not only enhances your Python programming skills but also deepens your understanding of IP addresses and their importance in networking. With this foundation, you can further expand the tool’s capabilities or integrate it into larger projects.

Leave a Comment

Join our Mailing list!

Get all latest news, exclusive deals and academy updates.