-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
81 lines (68 loc) · 2.69 KB
/
app.js
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
var dns = require('dns');
// treat first argument as (optional) interface IP or interface name
var iface = process.argv[2];
// set the interface option to a network interface name or IP to use a specific network interface
var mdns = require('multicast-dns')({ interface: iface });
// query cache
var cache = {};
// hardcoded TTL value
var ttl = 1800;
// maximum number cache entries
var max_cache_entries = 10000;
// handle Multicast DNS queries
mdns.on('query', function (query) {
var time = new Date().getTime() / 1000;
//console.log('time:', time);
//console.log('query:', query);
// clear the cache if it contains too many entries
if (Object.keys(cache).length > max_cache_entries) {
console.log('cache cleared');
cache = {};
}
query.questions.forEach(function (q) {
switch (q.type) {
case "A":
case "AAAA":
break;
default:
return;
}
// look for the result in our cache
var key = q.name + " [" + q.type + "]";
var value = cache[key];
if (typeof value != 'undefined') {
if ((time - value.time) < ttl) {
if (value.response != null) {
//console.log("cached: ", key, value.response);
mdns.response(value.response);
} else {
//console.log("ignoring: ", key);
}
return;
}
}
// resolve the query using DNS
dns.resolve(q.name, q.type, function (err, addresses) {
if (err != null) {
// on error, don't respond but add entry to our cache
console.log("not found: ", key, err);
cache[key] = { time: time, response: null };
} else {
// respond with the first address found
var address = addresses[0];
if (typeof address === 'undefined') {
// on empty record, just add entry to our cache
console.log("empty record: ", key, err);
cache[key] = { time: time, response: null };
} else {
var response = [{ name: q.name, type: q.type, ttl: ttl, data: address }];
console.log("resolved: ", key, response);
mdns.response(response);
// add entry to our cache
cache[key] = { time: time, response: null };
}
}
});
});
});
console.log("Listening for mDNS queries%s...", (iface !== undefined) ? " on " + iface : "");