使用 ip2region 地址定位库判断Ip地域

This commit is contained in:
2023-01-30 15:55:22 +08:00
parent c2024e15f5
commit 72bd738a1d
6 changed files with 74 additions and 33 deletions

View File

@@ -2,12 +2,12 @@
#include "xdb_searcher.h"
#include "ip2region.h"
int ip2region(char *xdb_file, char *ip)
char *ip2region(char *xdb_file, char *ip)
{
char *db_path = xdb_file;
xdb_vector_index_t *v_index;
xdb_searcher_t searcher;
char region_buffer[256], ip_buffer[16];
char region_buffer[256];
long s_time;
// 1、从 db_path 加载 VectorIndex 索引。
@@ -16,14 +16,14 @@ int ip2region(char *xdb_file, char *ip)
v_index = xdb_load_vector_index_from_file(db_path);
if (v_index == NULL) {
printf("failed to load vector index from `%s`\n", db_path);
return 1;
return NULL;
}
// 2、使用全局的 VectorIndex 变量创建带 VectorIndex 缓存的 xdb 查询对象
int err = xdb_new_with_vector_index(&searcher, db_path, v_index);
if (err != 0) {
printf("failed to create vector index cached searcher with errcode=%d\n", err);
return 2;
return NULL;
}
// 3、调用 search API 查询
@@ -32,8 +32,10 @@ int ip2region(char *xdb_file, char *ip)
err = xdb_search_by_string(&searcher, ip, region_buffer, sizeof(region_buffer));
if (err != 0) {
printf("failed search(%s) with errno=%d\n", ip, err);
return NULL;
} else {
printf("{region: %s, took: %d μs}", region_buffer, (int)(xdb_now() - s_time));
;
//printf("{region: %s, took: %dμs}", region_buffer, (int)(xdb_now() - s_time));
}
// 备注:并发使用,没一个线程需要单独定义并且初始化一个 searcher 查询对象。
@@ -41,5 +43,6 @@ int ip2region(char *xdb_file, char *ip)
// 4、关闭 xdb 查询器,如果是要关闭服务,也需要释放 v_index 的内存。
xdb_close(&searcher);
xdb_close_vector_index(v_index);
return 0;
return strdup(region_buffer);
}

View File

@@ -2,7 +2,7 @@
#define IP2REGION_H
int ip2region(char *xdb_file, char *ip);
char *ip2region(char *xdb_file, char *ip);
#endif