Project_2. Location using IP address (Python)

A project that will not take much time, but will give experience, and positive emotions.

Description

Using the script and the IP address, we calculate the location. It is impossible to determine the exact geolocation by IP address: all services that allow you to find information by IP can only determine the location at the city level. It is impossible to calculate your or any other exact home address from IP. This can only be done by law enforcement if they contact your ISP if you break the law.

Code

Let’s create 2 files that will have different functionality:

Let’s start with file 1. We are still importing what is required to implement the project.

import requests
import database

We remind you that database is the 2nd file.

The first function is main().

Function main() used to separate blocks of code in a program. Function use main() required in languages ​​like Java because it makes it easier to understand in what order code runs in a program. In python function main() writing is optional, but it improves the readability of the code.

The function takes as an argument a string that asks for an IP address. Then main() passes functions location() data.

def main(start: str):
    print(start)
    ip = input("IP address: ")
    try:
        new_data = location(ip)
        database.base(new_data)
    except ValueError:
        pass


if __name__ == "__main__":
    main("Enter the IP address")

Second function location() takes as an argument a string with an IP address. Sending a request using the method get.

GET is one of the most popular HTTP methods. Method GET indicates that an attempt is being made to retrieve data from a particular resource. To complete a request GETused requests.get().

Using .status_codeyou can see the status code that is returned from the server.

If 404 is displayed, then something went wrong.

The next step is to check for the correct IP address. If the IP address is incorrect, then returns the function main() with a new line telling you to enter a valid IP address. If everything is fine, then we create an empty list. With the help of a loop, we display all the data that is needed and add it to the list. The output will look like this.

Enter the IP address
IP address: 185.101.203.42
[Status]: success
[Country]: Болгария
[Countrycode]: BG
[Region]: 22
[Regionname]: Sofia-Capital
[City]: София
[Zip]: 1000
[Lat]: 42.6951
[Lon]: 23.325
[Timezone]: Europe/Sofia
[Isp]: SIA "Singularity Telecom"
[Org]: SIA "Singularity Telecom"
[As]: AS209372 SIA "Singularity Telecom"
[Query]: 185.101.203.42

We return a tuple with data.

def location(ip: str):
    response = requests.get(f"http://ip-api.com/json/{ip}?lang=ru")
    if response.status_code == 404:
        print("Oops")
    result = response.json()
    if result["status"] == "fail":
        return main("Enter the correct IP address")

    record = []

    for key, value in result.items():
        record.append(value)
        print(f"[{key.title()}]: {value}")
    return tuple(record)

Now let’s move on to the second file. database.pywhere the database will be created with new data added.

Import, as always, with us. The database will require a library sqlite3.

import sqlite3

We create a function that takes an argument in the form of a tuple.

First, we need to create a new database and open a database connection to allow sqlite3 work with her. Call sqlite3.connect()help us in that. If the database database.db does not exist, it will be implicitly created.

In order to execute SQL statements and retrieve results from SQL queries, we will need to use a database cursor. Call con.cursor() in business.

Now that we have a database connection and a cursor, we can create the database tables with the columns we need.

If there is already an IP address in the database, then output “Duplicate “. If not, then add new data to the database. Call conn.commit() will commit the transaction, so to speak. This is what the database will look like.

Table

Table

def base(data: tuple):
    conn = sqlite3.connect("database.db")
    cur = conn.cursor()
    cur.execute("""CREATE TABLE IF NOT EXISTS location(
    Status TEXT,
    Country TEXT,
    Countrycode TEXT,
    Region TEXT,
    Regionname TEXT,
    City TEXT,
    Zip INT,
    Lat REAL,
    Lon REAL,
    Timezone TEXT,
    Isp TEXT,
    Org TEXT,
    Auto_system TEXT,
    Query TEXT);
    """)
    try:
        check = cur.execute(f"SELECT * FROM location WHERE Query=?", (data[-1],))
        if len(list(*check)) == 0:
            cur.execute("INSERT INTO location VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);", data)
            conn.commit()
        else:
            print("Duplicate")
    except TypeError:
        pass

Scenario

main.py

# Location by IP
# Location search by IP address using Python
import requests
import database


def location(ip: str):
    response = requests.get(f"http://ip-api.com/json/{ip}?lang=ru")
    if response.status_code == 404:
        print("Oops")
    result = response.json()
    if result["status"] == "fail":
        return main("Enter the correct IP address")

    record = []

    for key, value in result.items():
        record.append(value)
        print(f"[{key.title()}]: {value}")
    return tuple(record)


def main(start: str):
    print(start)
    ip = input("IP address: ")
    try:
        new_data = location(ip)
        database.base(new_data)
    except ValueError:
        pass


if __name__ == "__main__":
    main("Enter the IP address")

database.py

import sqlite3


def base(data: tuple):
    conn = sqlite3.connect("database.db")
    cur = conn.cursor()
    cur.execute("""CREATE TABLE IF NOT EXISTS location(
    Status TEXT,
    Country TEXT,
    Countrycode TEXT,
    Region TEXT,
    Regionname TEXT,
    City TEXT,
    Zip INT,
    Lat REAL,
    Lon REAL,
    Timezone TEXT,
    Isp TEXT,
    Org TEXT,
    Auto_system TEXT,
    Query TEXT);
    """)
    try:
        check = cur.execute(f"SELECT * FROM location WHERE Query=?", (data[-1],))
        if len(list(*check)) == 0:
            cur.execute("INSERT INTO location VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);", data)
            conn.commit()
        else:
            print("Duplicate")
    except TypeError:
        pass

Conclusion

Some companies specialize in collecting information about the range of IP addresses from around the world. They sell this information in the form of consolidated databases that are easily integrated into any web server to quickly look up information about a country, region, city, or ISP. The accuracy of these databases ranges from 80 to 99.8% according to their own claims. This project showed how easy it is to write a small script that will collect the necessary information using such databases.

Link to GitHub

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *