Skip to content

Instantly share code, notes, and snippets.

@matcap
Created September 16, 2016 17:08
Show Gist options
  • Save matcap/fb27642545a8d2d1e8e986aec66cce73 to your computer and use it in GitHub Desktop.
Save matcap/fb27642545a8d2d1e8e986aec66cce73 to your computer and use it in GitHub Desktop.
Python IP geolocator
# Small python program to retrieve location and/or
# other infos about a internet address.
# Requires python3 and requests library.
# Thanks to freegeoip.net for its free JSON API.
import requests
import sys
GEOIP_URL = "http://freegeoip.net/json/"
arg_options = []
arg_hostname = ""
def geoip_json(hostname = ""):
global GEOIP_URL
try:
req = requests.get(GEOIP_URL + hostname)
return req.json()
except Exception as err:
print("ERROR: Cannot retrieve data from server " + GEOIP_URL, file=sys.stderr)
print(err, file=sys.stderr)
sys.exit(1)
def print_help(options = ""):
print( "Usage: geoip [hostname] [options...]\n"
" hostname: Address to locate (your address if not specified)\n"
"Special options:\n"
" -help: Shows this help\n"
" -raw: Outputs raw JSON data\n"
"Other available options:")
for name in options:
print(" -" + name)
# Check valid options
for arg in sys.argv[1:]:
if arg[0] == '-':
arg_options.append(arg[1:])
elif not arg_hostname:
arg_hostname = arg
else:
print("ERROR: Only one hostname is allowed ", file=sys.stderr)
sys.exit(1)
# Request from server
json_res = geoip_json(arg_hostname)
if arg_options.count("help"):
print_help(json_res)
elif arg_options.count("raw"):
print(json_res)
elif len(arg_options) > 0:
# Print each value on a different line
for arg in arg_options:
# Show value only if that field exists
if arg in json_res:
print(json_res[arg])
else:
# Print only important information
fmt = "Host: {}\nLocation: {}\nCountry: {}\nCoords: {}, {}"
print(fmt.format(
json_res["ip"],
json_res["city"] + ", " + json_res["region_name"] if json_res["city"] else json_res["region_name"],
json_res["country_name"],
json_res["latitude"],
json_res["longitude"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment