-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDNSCache.cpp
More file actions
79 lines (59 loc) · 1.68 KB
/
DNSCache.cpp
File metadata and controls
79 lines (59 loc) · 1.68 KB
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
#include "DNSCache.hpp"
#include "Logger.hpp"
#include <mutex>
using namespace std;
//////////////////////////////////////////////////////////////////////////
double DNSCache::EXPIRATION = 60 * 60 * 1;
DNSCache::Cache DNSCache::ms_cache;
static mutex gs_loggerMutex;
const DNSCache::Entry *DNSCache::Resolve(const string &dname) {
lock_guard<mutex> lock(gs_loggerMutex);
auto it(ms_cache.find(dname));
if (it != ms_cache.end()) {
auto curr = time(nullptr);
if (difftime(curr, it->second.ts) > EXPIRATION) {
ms_cache.erase(it);
return nullptr;
}
// 延长有效期:更新为当前时间戳
it->second.ts = curr;
return &(it->second);
}
return nullptr;
}
void DNSCache::Add(const std::string &dname, const addrinfo &ai) {
gs_loggerMutex.lock();
ms_cache.emplace(dname, &ai);
gs_loggerMutex.unlock();
}
bool DNSCache::Remove(const std::string &dname) {
lock_guard<mutex> lock(gs_loggerMutex);
auto it(ms_cache.find(dname));
if (it != ms_cache.end()) {
ms_cache.erase(it);
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
DNSCache::Entry::Entry(const addrinfo *ai_other) {
if (ai_other) {
ai = *ai_other;
ai.ai_addr = new sockaddr(*(ai_other->ai_addr));
// 没有使用这两个属性值
ai.ai_canonname = nullptr;
ai.ai_next = nullptr;
ts = time(nullptr);
}
else {
memset(&ai, 0, sizeof(addrinfo));
}
}
DNSCache::Entry::~Entry() {
if (IsOk()) {
delete ai.ai_addr;
}
}
bool DNSCache::Entry::IsOk() const {
return ai.ai_addr != nullptr;
}