pygeoip python code example
Example 1: python pygeoip example
def geo_ip(res_type, ip):
try:
import pygeoip
gi = pygeoip.GeoIP('GeoIP.dat')
if res_type == 'name':
return gi.country_name_by_addr(ip)
if res_type == 'cc':
return gi.country_code_by_addr(ip)
return gi.country_code_by_addr(ip)
except Exception as e:
print e
return ''
Example 2: python pygeoip example
def lookup(ip):
print("IP:", ip)
db = pygeoip.GeoIP("GeoLiteCity.dat")
geo_data = db.record_by_name(ip)
print("Country: " + geo_data["country_name"].encode("utf-8"))
if geo_data["city"]:
print("City: " + geo_data["city"].encode("utf-8"))
print("Longitude: " + str(geo_data["longitude"]).encode("utf-8"))
print("Latitude: " + str(geo_data["latitude"]).encode("utf-8"))
s = raw_input("\nDo you want to save the data in a .txt file? [Y/n]: ")
if s == "n" or s == "N" or s == "no" or s == "No" or s == "NO":
exit()
else:
f = open(str(ip) ,'w+')
c1 = "Country: " + geo_data["country_name"].encode("utf-8") + "\n"
f.write(str(c1))
if geo_data["city"]:
c2 = "City: " + geo_data["city"].encode("utf-8") + "\n"
f.write(str(c2))
l1 = "Longitude: " + str(geo_data["longitude"]).encode("utf-8") + "\n"
f.write(str(l1))
l2 = "Latitude: " + str(geo_data["latitude"]).encode("utf-8") +"\n"
f.write(str(l2))
f.close()