#include <maxminddb.h>
#include <stdlib.h>
#include <string.h>
#define CountryDB "/mnt/data/geolite2/GeoLite2-Country.mmdb"
/*
函数功能:通过ip返回ip所在的国家
参数:ip_address——待查询的ip
返回值:国家,如果为NULL,则代表查询出错或者未查出来;
*/
char* queryCountryByIP(char*ip_address)
{
MMDB_s mmdb;
int status = MMDB_open(CountryDB, MMDB_MODE_MMAP, &mmdb);
if (MMDB_SUCCESS != status){
fprintf(stderr, "\n Can't open %s - %s\n",CountryDB, MMDB_strerror(status));
if (MMDB_IO_ERROR == status)
fprintf(stderr, " IO error: %s\n", strerror(errno));
MMDB_close(&mmdb);
return NULL;
}
//进行ip-country的查询
int gai_error, mmdb_error;
MMDB_lookup_result_s result = MMDB_lookup_string(&mmdb, ip_address, &gai_error, &mmdb_error);
if (0 != gai_error) {
fprintf(stderr,"\n Error from getaddrinfo for %s - %s\n\n",ip_address, gai_strerror(gai_error));
MMDB_close(&mmdb);
return NULL;
}
if (MMDB_SUCCESS != mmdb_error) {
fprintf(stderr,"\n Got an error from libmaxminddb: %s\n\n",MMDB_strerror(mmdb_error));
MMDB_close(&mmdb);
return NULL;
}
//提取查询结果中的country部分
MMDB_entry_data_s *entry_data = malloc(sizeof(MMDB_entry_data_s));
int exit_code = 0;
if (result.found_entry) {
int status = MMDB_get_value(&result.entry, entry_data,"country","names","en",NULL);
if (MMDB_SUCCESS != status) {
fprintf(stderr,"Got an error looking up the entry data - %s\n", MMDB_strerror(status));
return NULL;
}
char * name_en =NULL;
if (entry_data->has_data) {
name_en = malloc(sizeof(char)*entry_data->data_size+1);
memcpy (name_en , entry_data->utf8_string , entry_data->data_size);
name_en[entry_data->data_size] = 0;
printf ("%s",name_en);
MMDB_close(&mmdb);
return name_en;
}
} else {
fprintf(stderr,"\n No entry for this IP address (%s) was found\n\n",ip_address);
MMDB_close(&mmdb);
return NULL;
}
}
int main(int argc, char **argv)
{
char* country = queryCountryByIP("112.233.242.1");
if(country)
printf("%s",country);
else
printf("null");
}