Skip to content

Instantly share code, notes, and snippets.

@xbenjii xbenjii/qry.js
Created Mar 24, 2016

Embed
What would you like to do?
import { createSocket } from 'dgram'
import { lookup } from 'dns';
const IPRe = /^\d+\.\d+\.\d+\.\d+$/;
const IPPortRe = /^\d+\.\d+\.\d+\.\d+\:\d+$/;
class Qry {
constructor(options) {
this.options = Object.assign({
bindAddress: 1337
}, options);
this.socket = createSocket('udp4');
this.socket.unref();
this.socket.bind(this.options.bindAddress);
this.queries = new Map();
this.socket.on('message', (buffer, rinfo) => {
const query = this.queries.get(`${rinfo.address}:${rinfo.port}`);
if(query) query(buffer);
});
}
send(buffer, address, port = 28960) {
if(typeof buffer === 'string') {
buffer = new Buffer(buffer, 'binary');
}
this.lookup(address)
.then((sendTo) => {
return new Promise((resolve) => {
const portToSend = sendTo.port || port;
this.socket.send(buffer, 0, buffer.length, portToSend, sendTo.address, () => {
this.queries.set(`${sendTo.address}:${portToSend}`, resolve);
});
});
})
}
lookup(address) {
return new Promise((resolve, reject) => {
if(address.match(IPRe)) {
resolve({ address});
} else if(address.match(IPPortRe)) {
const [address, port] = address.split(':');
resolve({ address, port });
} else {
lookup(host, (address) => {
resolve({ address});
});
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.