Created
March 24, 2016 12:19
-
-
Save xbenjii/89a6e59229908885bfc6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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