Security Scripting Challenge: Get IP Address Details

Published on: Sun, 15 May 2022


Scripting Challenge

Given an IP address like 1.1.1.1; write a program to return details about the IP address including city, region, country, AS number etc.

Solution

To solve this challenge we can take advantage of the websites like ipinfo.io, ipleak.net etc. We’ll go with ipinfo.io for this example as we can use their REST API to get response and parse it easily.

#!/usr/bin/env python3

# +-------------------------+
# | Program Name: ipinfo.py |
# | Author: Sudu            |
# +-------------------------+

import argparse
import json
import requests

parser = argparse.ArgumentParser()

parser.add_argument("-ip", type=str, default="1.1.1.1", help="Enter IP address to get more details")
args = parser.parse_args()


def ip_details_3(ip):
    result = requests.get(f"http://ipinfo.io/{ip}?token=[REDACTED]")
    return json.loads(result.text)


print(f"IP details for {args.ip}:\n")
for k,v in ip_details_3(args.ip).items():
    print(f"{k:<9}    {v}")

NOTE: The token value in above function is removed. Please obtain token for your own account by creating account with ipinfo.io

We can test our code and see the output get following output:

Result

$ ./ipinfo.py 
IP details for 1.1.1.1:

ip           1.1.1.1
hostname     one.one.one.one
anycast      True
city         Los Angeles
region       California
country      US
loc          34.0522,-118.2437
org          AS13335 Cloudflare, Inc.
postal       90076
timezone     America/Los_Angeles

That’s all folks! I hope you found this post helpful. :)

~ Amit


See more posts by tag: Linux Python Coding


Return to Blog Home