First, install Maxmind ip-location service ip-location
$ apt install geoip-bin geoip-database geoip-database-extra
now go to the Maxmind website create your account and download Geolite2-City-CSV
file.
now use the following tool to convert the Maxmind rev2 database to the rev1 database with the following tool
$ git clone https://github.com/hepictel/geolite2legacy.git
$ cd geolite2legacy/
$ chmod +x geolite2legacy.py
$ ./geolite2legacy.py -i /root/GeoLite2-City-CSV_20220125.zip -o GeoLite2-City.dat
$ ./geolite2legacy.py -i /root/GeoLite2-City-CSV_20220125.zip -o GeoLite2-City.dat
Move this newly created database file to the location /usr/share/GeoIP/GeoIPCity.dat
mv /usr/share/GeoIP/GeoIPCity.dat /root/
mv GeoLite2-City.dat /usr/share/GeoIP/GeoIPCity.dat
now try searching the IP
geoiplookup 213.207.186.42 | grep Rev | awk '{ print $6}' | head -c -2
write a small PHP script to convert it in an API
<?php
date_default_timezone_set("Europe/London");
$ip_address = $_SERVER['REMOTE_ADDR'];
if (strpos($ip_address, ".") === false) $family = "IPv6"; else $family = "IPv4";
$command = "geoiplookup $ip_address | grep Rev | awk '{ print $6}' | head -c -2";
$ip_location=NULL;
if ($family == "IPv4") exec($command,$ip_location, $ip_location_code);
$data = [ 'ip_address' => $ip_address, 'family' => $family, 'ip_location' => $ip_location[0], 'time' => date("c") ];
header('Content-Type: application/json');
echo json_encode($data);
?>
Enjoy ;)