-
Notifications
You must be signed in to change notification settings - Fork 0
/
dns_resolvers.c
114 lines (97 loc) · 2.64 KB
/
dns_resolvers.c
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
106
107
108
109
110
111
112
113
114
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
/*
* Functions: get_ipaddr_by_name(), get_name_by_ipaddr()
* are wrappers over getaddrinfo() and getnameinfo()
* respectively.
*
*/
/*
* Function: get_ipaddr_by_name()
* ------------------------------
* Makes a DNS resolution of domain name.
*
* name - domain name (e.g. google.com)
*
* out - pointer to an in_addr_t to `return`, returns the first entry
* of getaddrinfo() list.
*
* canon_name - pointer to string for canon_name, will be filled if not NULL
*
* canon_name_size - size out output buffer
*
* returns: 0 - success
* OTHER - error, use gai_strerror()
* to discover a particular error
*
*/
int get_ipaddr_by_name(const char *name, in_addr_t *out,
char *canon_name, size_t canon_name_size) {
struct addrinfo hints, *result;
int errcode;
memset (&hints, 0, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_flags |= AI_CANONNAME;
errcode = getaddrinfo(name, NULL, &hints, &result);
if (errcode != 0) {
return errcode;
}
*out = ((struct sockaddr_in *)result->ai_addr)->sin_addr.s_addr;
if (canon_name) {
strncpy(canon_name, result->ai_canonname, canon_name_size);
}
freeaddrinfo(result);
return 0;
}
/*
* Function: get_name_by_ipaddr()
* ------------------------------
* Resolve a hostname by IPv4. Caches up to 10 results.
*
* ip - input IPv4 address
*
* host - pointer to ouput hostname buffer
*
* host_len - output buffer len
*
* returns: 0 - success
* OTHER - error, use gai_strerror()
* to discover a particular error
*
*/
int get_name_by_ipaddr(in_addr_t ip, char *host, size_t host_len) {
struct help {
in_addr_t addr;
char hostname[NI_MAXHOST];
};
static struct help storage[10] = { 0 }; /* No lru, man, no lru */
static int count = 0;
// Lookup in cache
for (int i = 0; i < count; i++) {
if (storage[i].addr == ip) {
// Found in cache
strncpy(host, storage[i].hostname, host_len);
return 0;
}
}
struct sockaddr_in addr;
int ret_code;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = ip;
ret_code = getnameinfo((struct sockaddr*)&addr,
sizeof addr,
host, host_len,
NULL, 0, 0);
if (ret_code != 0) {
return ret_code;
}
// Append to cache
if (count < 10) {
storage[count].addr = ip;
strncpy(storage[count].hostname, host, NI_MAXHOST);
count++;
}
return 0;
}