1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "../include/maxminddb.h"
#define xdebug(fmt, arg...) \
do{ \
printf("%s %d : ", __FILE__, __LINE__); \
printf(fmt, ##arg); \
printf("\n"); \
}while(0)
/*
* Query the COUNTRY field of an IP address in mmdb file.
*/
int main(int argc, char **argv)
{
if(argc < 2)
{
xdebug("Usage : %s dbfilename IP", argv[0]);
return 0;
}
char *filename = argv[1]; // mmdb file path
char *ip_address = argv[2]; // input IP address
MMDB_s mmdb;
int status = MMDB_open(filename, MMDB_MODE_MMAP, &mmdb);
if(MMDB_SUCCESS != status)
{
fprintf(stderr, "\n Can't open %s - %s\n",
filename, MMDB_strerror(status));
if(MMDB_IO_ERROR == status)
{
fprintf(stderr, "IO error: %s\n", strerror(errno));
}
exit(1);
}
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));
exit(2);
}
if (MMDB_SUCCESS != mmdb_error)
{
fprintf(stderr,
"\n Got an error from libmaxminddb: %s\n\n",
MMDB_strerror(mmdb_error));
exit(3);
}
MMDB_entry_data_s entry_data;
int exit_code = 0;
if (result.found_entry)
{
int status = MMDB_get_value(&result.entry, &entry_data, "COUNTRY", NULL);
if (MMDB_SUCCESS != status)
{
fprintf(
stderr,
"Got an error looking up the entry data - %s\n",
MMDB_strerror(status));
exit_code = 4;
goto end;
}
if (entry_data.has_data)
{
char *name_en = malloc(sizeof(entry_data.data_size + 1));
memset(name_en, '\0', sizeof(entry_data.data_size + 1));
memcpy(name_en, entry_data.utf8_string, entry_data.data_size);
printf ("%s\n", name_en);
free(name_en);
name_en = NULL;
}
}
else
{
fprintf(
stderr,
"\n No entry for this IP address (%s) was found\n\n",
ip_address);
exit_code = 5;
}
end:
MMDB_close(&mmdb);
exit(exit_code);
}
|