Skip to content

Instantly share code, notes, and snippets.

@Sulter
Last active November 7, 2020 21:40
Show Gist options
  • Select an option

  • Save Sulter/7459117 to your computer and use it in GitHub Desktop.

Select an option

Save Sulter/7459117 to your computer and use it in GitHub Desktop.
A small python script that finds gelocation of IP addresses and host names, using http://freegeoip.net/.
#!/usr/bin/env python
import sys
import urllib.request
import json
def get_info(adress):
print("************************************************")
api = "http://freegeoip.net/json/" + adress
try:
result = urllib.request.urlopen(api).read()
result = str(result)
result = result[2:len(result)-3]
result = json.loads(result)
except:
print("Could not find: ", adress)
return None
print(adress)
print("IP: ", result["ip"])
print("Country Name: ", result["country_name"])
print("Country Code: ", result["country_code"])
print("Region Name: ", result["region_name"])
print("Region Code: ", result["region_code"])
print("City: ", result["city"])
print("Zip Code: ", result["zip_code"])
print("Latitude: ", result["latitude"])
print("Longitude: ", result["longitude"])
print("Location link: " + "http://www.openstreetmap.org/#map=11/" + str(result["latitude"]) +"/" + str(result["longitude"]))
def showhelp():
print ("Usage: geoip address [address]...")
print ("find gelocation of IP addresses and host names, using http://freegeoip.net/")
if __name__ == "__main__": #code to execute if called from command-line
inputs = sys.argv
if len(inputs) < 2 or "--help" in inputs:
showhelp()
else:
for address in inputs[1:]:
get_info(address)
print("************************************************")
@Igelchen1

Copy link
Copy Markdown

Nice one! saved me some time. Still the zipcode request changed: Change to result["zip_code"] and its working again.

@py-ranoid

py-ranoid commented Jun 23, 2018

Copy link
Copy Markdown

This doesn't work anymore.

This API endpoint is deprecated and will stop working on July 1st, 2018. For more information please visit: https://github.com/apilayer/freegeoip#readme

@kupp1

kupp1 commented Jun 24, 2018

Copy link
Copy Markdown

Ya! Thanks for Sulter!
@py-ranoid At me all works

@namelessbillionaire

Copy link
Copy Markdown

New API Endpoint as of August 30, 2018 is

url = 'http://api.ipstack.com/[IP_ADDRESS]?access_key=[ACCESS_KEY]'

ghost commented Nov 9, 2018

Copy link
Copy Markdown

Hey @chrisjuliales
What about the [ACCESS_KEY]?

@drewlr

drewlr commented Jun 7, 2020

Copy link
Copy Markdown

Maybe the API results changed since, but would replace

result = urllib.request.urlopen(api).read()
result = str(result) 
result = result[2:len(result)-3]
result = json.loads(result)

with

result = urllib.request.urlopen(api).read()
json.loads(result.decode('utf-8'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment