Files
LumberJack_TUI/ip_to_geo/ip_to_geo.cpp

59 lines
1.8 KiB
C++

#include "ip_to_geo.hpp"
#include <exception>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <map>
#include <string>
#include "../third_party/include/GeoLite2PP.hpp"
void load_env_file(const std::string& env_path) {
std::ifstream file(env_path);
if (!file.is_open()) {
std::cerr << "Warning: Could not open " << env_path << " file." << std::endl;
return;
}
std::string line;
while (std::getline(file, line)) {
// Skip empty lines or comments
if (line.empty() || line[0] == '#') continue;
std::size_t delimiter_pos = line.find('=');
if (delimiter_pos != std::string::npos) {
std::string key = line.substr(0, delimiter_pos);
std::string value = line.substr(delimiter_pos + 1);
// Set the variable globally in the execution environment
setenv(key.c_str(), value.c_str(), 1);
}
}
}
loc_data iplookup(const std::string& ip) {
// 1. Load variables from the local .env file
load_env_file();
// 2. Fetch the path out of the environment variables
const char* env_db_path = std::getenv("DB_PATH");
// Fallback to a default path if the environment variable wasn't set
std::string db_path = (env_db_path != nullptr) ? env_db_path : "data/GeoLite2-City.mmdb";
loc_data location;
try {
GeoLite2PP::DB db(db_path);
std::map<std::string, std::string> geo_data = db.get_all_fields(ip, "en");
location.country = geo_data["country"];
location.subdivision = geo_data["subdivision"];
location.city = geo_data["city"];
location.latitutde = geo_data["latitude"];
location.longitude = geo_data["longitude"];
}
catch (const std::exception& e) {
std::cerr << "Database failed to load: " << e.what() << std::endl;
}
return location;
};