How to Get IP Address Information Using Python [2021]



What is an IP Address?

An IP Address (Internet Protocol Address) is a numeric label used by the Internet Series Provider (ISP) to identify you when you surf the Internet. It serves two main functions, host or network interface identification and location addressing. The IPv4 address consists of 32 bits. However, due to the rapid spread of the Internet, the 128-bit IPv6 address system was introduced.

IP Address Location - How to get IP Address Information Using Python[2021] - Image Resource Wikipedia

1. Python IPv4/IPv6 manipulation library

is an in-built library that comes with python. This simplifies the handling of the functions and various functions related to class IP addresses. Checking whether two hosts are on the same subnet, reactivating through all the hosts in a particular subnet, the functions here are as follows.

Import-Module

import ipaddress


Validity check

This checks if the IP address is correct. If this is not an IPv4 or IPv6 address then an error has occurred
>>> ipaddress.ip_address("192.168.8.10")
IPv4Address('192.168.8.10')                  # IPv4 Address             
>>>
>>> ipaddress.ip_address("2404:6800:4009:82b::200e")
IPv6Address('2404:6800:4009:82b::200e')      # IPv6 Address

check_ip_validity.py
#!/usr/bin/env python3

import ipaddress
ip = input("IP Address : ")

def ip_validator(ip_addr):
    try:
        ipaddress.ip_address(ip_addr)
        return True
        
    except ValueError:  
        return False

if (ip_validator(ip)):
    print(ip, "is valid Ip Address")
else:
    print(ip, "Invalid Ip Address")

In addition, more information can be obtained from the following codes.
>>> addr = ipaddress.ip_address("2404:6800:4009:82b::200e")
>>> addr.compressed
'2404:6800:4009:82b::200e'
>>> addr.exploded
'2404:6800:4009:082b:0000:0000:0000:200e'
>>> addr.is_global
True
>>> addr.is_loopback
False
>>> addr.is_multicast
False
>>> addr.is_private
False
>>> addr.is_reserved
False
>>> addr.version
6

This module allows you to find out the validity and type of an IP address. This does not require a network connection.

2. Python Socket Library

This module is a low-level networking interface built with Python. Let’s get the details of an Internet Protocol address using this ‌module.

Import-Module

import socket


Get Your IP Address

If your device has a network interface installed, it displays the IP address provided by the network.
>>> socket.gethostbyname(socket.gethostname())
'192.168.10.128'

TIP: Let’s get the IP addresses of any web server
>>> socket.gethostbyname("google.com")
'142.250.192.142'


3. Get IP Address Location using Third Party API ( Application Programming Interface )

The IP address obtained using the socket module is a static address. When you retrieve data over the Internet, it is obtained through the ISP. But that address is not open to the Internet. This is because when a request is made to provide a web page to the ISP, they will retrieve it from the Internet and deliver it to you. It will then give you another public address. It’s a dynamic address. Websites identify you by that address. Location cannot be obtained correctly from this Dynamic IP Address. It then shows you the approximate location of your ISP. In this section, we will introduce you to a new Third Party API.

For this, you need to install a Pypi Package
pip install requests

ip_information.py
import requests

ip = input("Target IP Address : ").strip()

url = "http://ip-api.com/json/{0}"
response = requests.get(url.format(ip)).json()

for key in response:
    print("{0: <15} - {1}".format(key, response[key]))

Output
If you left Target IP Address without typing anything, you will get the details related to your address.
PS C:\Users\iLabAcademy> python ip_information.py
Target IP Address : 
status          - success
country         - United States
countryCode     - US
region          - CA
regionName      - California
city            - Los Angeles
zip             - 90006
lat             - 34.0447
lon             - -118.2946
timezone        - America/Los_Angeles
isp             - Cellco Partnership DBA Verizon Wireless
org             - Cellco Partnership DBA Verizon Wireless
as              - AS22394 Cellco Partnership DBA Verizon Wireless
query           - 174.193.214.3

Output – 2
Otherwise, if you provided a web address or other address, the details will be displayed.
PS C:\Users\iLabAcademy> python ip_information.py
Target IP Address : www.google.com
status          - success
country         - United Kingdom
countryCode     - GB
region          - ENG
regionName      - England
city            - London
zip             - W1B
lat             - 51.5074
lon             - -0.127758
timezone        - Europe/London
isp             - Google LLC
org             - Google LLC
as              - AS15169 Google LLC
query           - 142.250.200.4

Good. We have completed a very important tutorial. But there are a number of things you need to keep in mind. No one can hide on the internet. No matter how many tricks you use like VPN, Proxy Chain, it can only delay finding out about you. Because all these systems were made by man. Therefore, do not act in a way that harms anyone’s privacy.
If you have problems with this article, please comment below. I am ready to answer.

Suggested Video


Post a Comment

0 Comments