dns-suite.js/examples/listen.js

77 lines
1.6 KiB
JavaScript

'use strict';
var dgram = require('dgram');
var socket = dgram.createSocket({
type: 'udp4'
, reuseAddr: true
});
var dns = require('dns-js');
//var DNSPacket = dns.DNSPacket;
var broadcast = '224.0.0.251'; // mdns
var port = 5353; // mdns
// ex: pad('11111', 8, '0')
function pad(str, len, ch) {
while (str.length < len) {
str = ch + str;
}
return str;
}
function binaryAgent(str) {
var binString = '';
str.split(' ').map(function(bin) {
binString += String.fromCharCode(parseInt(bin, 2));
});
return binString;
}
socket.on('message', function (message, rinfo) {
console.log('Received %d bytes from %s:%d\n',
message.length, rinfo.address, rinfo.port);
//console.log(msg.toString('utf8'));
message.forEach(function(byte){
console.log(pad(byte.toString(2), 8,'0'));
});
// console.log(message.toString('hex'));
// console.log(message.toString('ascii'));
var packets;
try {
packets = dns.DNSPacket.parse(message);
}
catch (er) {
//partial, skip it
console.error(er);
return;
}
if (!Array.isArray(packets)) { packets = [packets]; }
require('./cloud-respond.js').respond(socket, packets, rinfo);
// console.log(packets);
// console.log('\n');
});
socket.bind(port, function () {
console.log('***********************************')
console.log('bound on', port);
console.log('***********************************')
console.log('bound on', this.address());
socket.setBroadcast(true);
socket.addMembership(broadcast);
// buf.forEach parseInt(byte.toString('hex'), 16).toString(2);
});