From 3c989de2074a1bc103be0dafb5b11c87bbba8351 Mon Sep 17 00:00:00 2001 From: Brian White Date: Sat, 27 May 2017 21:44:03 -0400 Subject: [PATCH] dns: use faster IP address type check on results PR-URL: https://github.com/nodejs/node/pull/13261 Reviewed-By: Roman Reiss Reviewed-By: James M Snell --- lib/dns.js | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/lib/dns.js b/lib/dns.js index 812045bab80789..6fcf37a85e6c12 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -60,6 +60,31 @@ function errnoException(err, syscall, hostname) { return ex; } +const digits = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0-15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 32-47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48-63 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 64-79 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80-95 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 96-111 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 112-127 +]; +function isIPv4(str) { + if (!digits[str.charCodeAt(0)]) return false; + if (str.length === 1) return false; + if (str.charCodeAt(1) === 46/*'.'*/) + return true; + else if (!digits[str.charCodeAt(1)]) + return false; + if (str.length === 2) return false; + if (str.charCodeAt(2) === 46/*'.'*/) + return true; + else if (!digits[str.charCodeAt(2)]) + return false; + return (str.length > 3 && str.charCodeAt(3) === 46/*'.'*/); +} + function onlookup(err, addresses) { if (err) { @@ -68,25 +93,26 @@ function onlookup(err, addresses) { if (this.family) { this.callback(null, addresses[0], this.family); } else { - this.callback(null, addresses[0], addresses[0].indexOf(':') >= 0 ? 6 : 4); + this.callback(null, addresses[0], isIPv4(addresses[0]) ? 4 : 6); } } function onlookupall(err, addresses) { - var results = []; if (err) { return this.callback(errnoException(err, 'getaddrinfo', this.hostname)); } + var family = this.family; for (var i = 0; i < addresses.length; i++) { - results.push({ - address: addresses[i], - family: this.family || (addresses[i].indexOf(':') >= 0 ? 6 : 4) - }); + const addr = addresses[i]; + addresses[i] = { + address: addr, + family: family || (isIPv4(addr) ? 4 : 6) + }; } - this.callback(null, results); + this.callback(null, addresses); }