90 lines
2.2 KiB
JavaScript
90 lines
2.2 KiB
JavaScript
|
'use strict';
|
||
|
|
||
|
var dnsjs = require('dns-suite');
|
||
|
var crypto = require('crypto');
|
||
|
var dgram = require('dgram');
|
||
|
|
||
|
function request(queryAb, opts) {
|
||
|
var handlers = {};
|
||
|
var server = dgram.createSocket({
|
||
|
type: 'udp4'
|
||
|
, reuseAddr: true
|
||
|
});
|
||
|
|
||
|
handlers.onError = function (err) {
|
||
|
if (opts.onError) { opts.onError(err); }
|
||
|
server.close();
|
||
|
};
|
||
|
handlers.onMessage = function (bin) {
|
||
|
if (!opts.mdns) {
|
||
|
server.close();
|
||
|
}
|
||
|
|
||
|
if (opts.onMessage) { opts.onMessage(bin); }
|
||
|
};
|
||
|
handlers.onListening = function () {
|
||
|
/*jshint validthis:true*/
|
||
|
var server = this;
|
||
|
var nameservers;
|
||
|
var index;
|
||
|
server.nameserver = opts.nameserver;
|
||
|
|
||
|
if (!server.nameserver) {
|
||
|
nameservers = require('dns').getServers();
|
||
|
index = crypto.randomBytes(2).readUInt16BE(0) % nameservers.length;
|
||
|
server.nameserver = nameservers[index];
|
||
|
}
|
||
|
|
||
|
if (opts.mdns || '224.0.0.251' === opts.nameserver) {
|
||
|
server.setBroadcast(true);
|
||
|
server.addMembership(opts.nameserver);
|
||
|
}
|
||
|
|
||
|
if (opts.onListening) { opts.onListening.apply(server); }
|
||
|
|
||
|
server.send(Buffer.from(queryAb), opts.port, server.nameserver, function () {
|
||
|
if (opts.onSent) { opts.onSent({ port: opts.port, nameserver: server.nameserver }); }
|
||
|
});
|
||
|
};
|
||
|
|
||
|
server.on('error', handlers.onError);
|
||
|
server.on('message', handlers.onMessage);
|
||
|
server.on('listening', handlers.onListening);
|
||
|
|
||
|
// 0 dns request
|
||
|
// 53 dns server
|
||
|
// 5353 mdns
|
||
|
if (opts.mdns) {
|
||
|
server.bind(opts.port /*5353*/);
|
||
|
setTimeout(function () {
|
||
|
server.close();
|
||
|
}, opts.timeout || (5 * 1000));
|
||
|
}
|
||
|
else {
|
||
|
server.bind(0);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function requestJson(query, opts) {
|
||
|
var queryAb = dnsjs.DNSPacket.write(query);
|
||
|
var options = {
|
||
|
onError: opts.onError
|
||
|
, onMessage: function (nb) {
|
||
|
var packet = dnsjs.DNSPacket.parse(nb.buffer.slice(nb.byteOffset, nb.byteOffset + nb.byteLength));
|
||
|
|
||
|
opts.onMessage(packet);
|
||
|
}
|
||
|
, onListening: opts.onListening
|
||
|
, onSent: opts.onSent
|
||
|
, mdns: opts.mdns
|
||
|
, nameserver: opts.nameserver
|
||
|
, port: opts.port
|
||
|
, timeout: opts.timeout
|
||
|
};
|
||
|
|
||
|
return request(queryAb, options);
|
||
|
}
|
||
|
|
||
|
module.exports.request = request;
|
||
|
module.exports.requestJson = requestJson;
|