Skip to content

Instantly share code, notes, and snippets.

@k4yt3x
Last active May 25, 2021 07:20
Show Gist options
  • Save k4yt3x/20c3113991557446e13eeead6022c9bb to your computer and use it in GitHub Desktop.
Save k4yt3x/20c3113991557446e13eeead6022c9bb to your computer and use it in GitHub Desktop.
IPInfo IP Information Lookup Script

ipinfo

Description

ipinfo fetches and parses current or specified IP address information.

Screenshots

image

Usage

usage: ipinfo [-h] [-p {ipinfo,ifconfig}] [-4 | -6] [hostname]

positional arguments:
  hostname              IP address or hostname to lookup, defaults to the current machine's IP address if omitted

optional arguments:
  -h, --help            show this help message and exit
  -p {ipinfo,ifconfig}, --provider {ipinfo,ifconfig}
                        choose IP lookup service provider
  -4                    Force IPv4
  -6                    Force IPv6

Code

Add this into your shell configuration file (e.g., ~/.bashrc or ~/.zshrc).

# ipinfo fetches and parses current or specified IP address information
# version 3.1.0
function ipinfo() {
    python3 - $@ << EOF
import argparse, json, socket, subprocess, sys

parser = argparse.ArgumentParser(prog="ipinfo")
parser.add_argument("hostname", nargs="?", help="IP address or hostname to lookup, defaults to the current machine's IP address if omitted", default="")
parser.add_argument("-p", "--provider", choices=["ipinfo", "ifconfig"], help="choose IP lookup service provider", default="ifconfig")
ip_family_group = parser.add_mutually_exclusive_group()
ip_family_group.add_argument("-4", action="store_true", help="Force IPv4")
ip_family_group.add_argument("-6", action="store_true", help="Force IPv6")
args = parser.parse_args()

try: ip = socket.getaddrinfo(args.hostname, None, socket.AF_INET6 if args.__dict__["6"] is True else socket.AF_INET if args.__dict__["4"] is True else 0)[0][4][0] if args.hostname != '' else ''
except socket.gaierror: print('Hostname cannot be resolved', file=sys.stderr); sys.exit(1)

PROVIDERS_URL = {"ipinfo": "https://ipinfo.io/{ip}", "ifconfig": "https://ifconfig.co/json?ip={ip}"}
if ip == '': curl_process = subprocess.run(["/usr/bin/curl", "-sSL", "-6" if args.__dict__["6"] is True else "-4" if args.__dict__["4"] is True else "", PROVIDERS_URL[args.provider].format(ip=ip)], capture_output=True)
else: curl_process = subprocess.run(["/usr/bin/curl", "-sSL", PROVIDERS_URL[args.provider].format(ip=ip)], capture_output=True)
if curl_process.returncode != 0: print(f"cURL returned error code {curl_process.returncode}", file=sys.stderr); print(curl_process.stderr.decode().strip(), file=sys.stderr); sys.exit(1)

try: json_result = json.loads(curl_process.stdout.decode())
except json.decoder.JSONDecodeError:
    print("Failed to parse server response", file=sys.stderr)
    print(f"Server response: {curl_process.stdout.decode()}", file=sys.stderr)
    sys.exit(1)

for key, value in json_result.items():
    print("{0:15}{1}".format(key.upper(), value))
EOF
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment