文章详情
GeoLite本地ip数据库分辨ip所属国籍(C++)
Posted on 2024-09-06 21:39:29 by 主打一个C++
//项目需求为了效率用到本地ip数据库来分辨ip所属国籍,
//用到GeoLite2-Country.mmdb数据库 官网:https://www.maxmind.com/en/home
//根据需求,我下载的是 GeoLite2 Country -> GZIP
//下载C调用库->地址: https://github.com/maxmind/libmaxminddb ,项目目录下创建include目录,解压到include
//添加外部包含目录:
$(SolutionDir)include;
//必备头文件:
#include <iostream>
#include <maxminddb.h>
//独立函数判断是否中国IP:
bool is_china_ip(const std::string& ip, const std::string& db_path) {
MMDB_s mmdb;
int status = MMDB_open(db_path.c_str(), MMDB_MODE_MMAP, &mmdb);
if (status != MMDB_SUCCESS) {
std::cerr << "警告:数据库打开失败: " << MMDB_strerror(status) << std::endl;
return false;
}
int gai_error, mmdb_error;
MMDB_lookup_result_s result = MMDB_lookup_string(&mmdb, ip.c_str(), &gai_error, &mmdb_error);
if (gai_error != 0) {
std::cerr << "DNS解析错误: " << gai_strerror(gai_error) << std::endl;
MMDB_close(&mmdb);
return false;
}
if (mmdb_error != MMDB_SUCCESS) {
std::cerr << "数据库查找错误: " << MMDB_strerror(mmdb_error) << std::endl;
MMDB_close(&mmdb);
return false;
}
if (result.found_entry) {
MMDB_entry_data_s entry_data;
int status = MMDB_get_value(&result.entry, &entry_data, "country", "iso_code", NULL);
if (status == MMDB_SUCCESS && entry_data.has_data) {
if (entry_data.type == MMDB_DATA_TYPE_UTF8_STRING) {
std::string iso_code(entry_data.utf8_string, entry_data.data_size);
MMDB_close(&mmdb);
return iso_code == "CN";
}
}
}
MMDB_close(&mmdb);
return false;
}
//简单调用
int main() {
std::string db_path = "./GeoLite2-Country.mmdb";
std::string test_ip = "1.174.45.180";
std::cout << (is_china_ip(test_ip, db_path) ? "是中国IP" : "国外IP") << std::endl;
return 0;
}
坑:windows调用下可能需要修改些代码,遗憾的是一顿修改,忘了记录🤡,下面有修改过的windows调用库
*转载请注明出处:原文链接:https://cpp.vin/page/27.html