Skip to content

Instantly share code, notes, and snippets.

@stefanpejcic
Created March 28, 2024 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanpejcic/af5a4efd9cdce4d78779b34852ef55e4 to your computer and use it in GitHub Desktop.
Save stefanpejcic/af5a4efd9cdce4d78779b34852ef55e4 to your computer and use it in GitHub Desktop.
Use geoip db to check country code for ip
import os
import json
import socket
from flask import Flask, Response, abort, render_template, request, send_file, g, jsonify, session, url_for, flash, redirect, get_flashed_messages
import subprocess
import datetime
# apt-get install geoip-bin
@app.route('/ip/<ip_address>')
def get_country_for_ip(ip_address):
try:
ip_lookup_result = subprocess.check_output(['geoiplookup', ip_address]).decode('utf-8')
if "GeoIP Country Edition: IP Address not found" in ip_lookup_result:
country_code, country_name = None, None
else:
country_info = ip_lookup_result.split(': ')[-1].strip()
country_code, country_name = country_info.split(', ')
result = {"ip": ip_address, "country": country_code}
return jsonify(result)
except subprocess.CalledProcessError as e:
print(f"Error executing geoiplookup: {e}")
return jsonify({"error": "Failed to retrieve country information for the provided IP address."}), 500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment