]> git.ipfire.org Git - people/ms/libloc.git/blob - src/test-country.c
96e1c3bce066a70f7be6869259dd8ede1ba3db69
[people/ms/libloc.git] / src / test-country.c
1 /*
2 libloc - A library to determine the location of someone on the Internet
3
4 Copyright (C) 2019 IPFire Development Team <info@ipfire.org>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15 */
16
17 #include <errno.h>
18 #include <stdio.h>
19 #include <stddef.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include <loc/libloc.h>
24 #include <loc/database.h>
25 #include <loc/network.h>
26 #include <loc/writer.h>
27
28 int main(int argc, char** argv) {
29 struct loc_country* country;
30 int err;
31
32 struct loc_ctx* ctx;
33 err = loc_new(&ctx);
34 if (err < 0)
35 exit(EXIT_FAILURE);
36
37 // Create a database
38 struct loc_writer* writer;
39 err = loc_writer_new(ctx, &writer);
40 if (err < 0)
41 exit(EXIT_FAILURE);
42
43 // Create a country
44 err = loc_writer_add_country(writer, &country, "T1");
45 if (err) {
46 fprintf(stderr, "Could not create country\n");
47 exit(EXIT_FAILURE);
48 }
49
50 // Set name & continent
51 loc_country_set_name(country, "Testistan");
52 loc_country_set_continent_code(country, "XX");
53
54 // Free country
55 loc_country_unref(country);
56
57 FILE* f = fopen("test.db", "w");
58 if (!f) {
59 fprintf(stderr, "Could not open file for writing: %s\n", strerror(errno));
60 exit(EXIT_FAILURE);
61 }
62
63 err = loc_writer_write(writer, f);
64 if (err) {
65 fprintf(stderr, "Could not write database: %s\n", strerror(-err));
66 exit(EXIT_FAILURE);
67 }
68 fclose(f);
69
70 loc_writer_unref(writer);
71
72 // And open it again from disk
73 f = fopen("test.db", "r");
74 if (!f) {
75 fprintf(stderr, "Could not open file for reading: %s\n", strerror(errno));
76 exit(EXIT_FAILURE);
77 }
78
79 struct loc_database* db;
80 err = loc_database_new(ctx, &db, f);
81 if (err) {
82 fprintf(stderr, "Could not open database: %s\n", strerror(-err));
83 exit(EXIT_FAILURE);
84 }
85
86 // Lookup an address in the subnet
87 err = loc_database_get_country(db, &country, "T1");
88 if (err) {
89 fprintf(stderr, "Could not find country T1\n");
90 exit(EXIT_FAILURE);
91 }
92 loc_country_unref(country);
93
94 loc_database_unref(db);
95 loc_unref(ctx);
96
97 return EXIT_SUCCESS;
98 }