Skip to content

Instantly share code, notes, and snippets.

@djmitche
Last active February 3, 2017 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djmitche/6977bd19fb37b99510af4fb4c9a1dc2c to your computer and use it in GitHub Desktop.
Save djmitche/6977bd19fb37b99510af4fb4c9a1dc2c to your computer and use it in GitHub Desktop.
ip2name
node_modules/
dns = require('dns');
const reverse = ip => new Promise((resolve, reject) => {
dns.reverse(ip, (err, hostnames) => {
if (err) {
reject(err);
} else {
resolve(hostnames);
}
});
});
const resolve = name => new Promise((resolve, reject) => {
dns.resolve4(name, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
/**
* Get the hostname corresponding to the given IP. This hostname
* must be the only hostname to which that IP resolves in reverse DNS (via
* PTR records), and the hostname must only resolve to the given IP.
*/
module.exports = ip => {
return reverse(ip).then(hostnames => {
if (hostnames.length > 1) {
throw new Error(`Several hostnames found for ${ip}`);
} else if (hostnames.length === 0) {
throw new Error(`No hostnames found for ${ip}`);
}
return resolve(hostnames[0]).then(result => {
if (result.length > 1) {
throw new Error(`Hostname for ${ip} maps back to several IPs`);
} else if (result.length === 0 || result[0] !== ip) {
throw new Error(`Hostname for ${ip} does not map back to ${ip}`);
}
return hostnames[0]; // success!
});
}).catch(err => {
console.error(err);
});
};
{
"name": "ip2name",
"version": "1.0.0",
"description": "Convert an IP to a name checking forward and reverse resolution",
"main": "index.js",
"files": [
"index.js"
],
"scripts": {
"test": "mocha --ui tdd test.js"
},
"author": "Dustin J. Mitchell",
"license": "MPL-2.0"
}
require('mocha');
assert = require('assert');
ip2name = require('./index');
suite("convert", function() {
test("8.8.8.8", function() {
return ip2name('8.8.8.8').then(name => {
assert.equal(name, 'google-public-dns-a.google.com');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment