You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

isInNet.js 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Module dependencies.
  3. */
  4. var dns = require('dns');
  5. var Netmask = require('netmask').Netmask;
  6. /**
  7. * Module exports.
  8. */
  9. module.exports = isInNet;
  10. isInNet.async = true;
  11. /**
  12. * True iff the IP address of the host matches the specified IP address pattern.
  13. *
  14. * Pattern and mask specification is done the same way as for SOCKS configuration.
  15. *
  16. * Examples:
  17. *
  18. * ``` js
  19. * isInNet(host, "198.95.249.79", "255.255.255.255")
  20. * // is true iff the IP address of host matches exactly 198.95.249.79.
  21. *
  22. * isInNet(host, "198.95.0.0", "255.255.0.0")
  23. * // is true iff the IP address of the host matches 198.95.*.*.
  24. * ```
  25. *
  26. * @param {String} host a DNS hostname, or IP address. If a hostname is passed,
  27. * it will be resoved into an IP address by this function.
  28. * @param {String} pattern an IP address pattern in the dot-separated format mask.
  29. * @param {String} mask for the IP address pattern informing which parts of the
  30. * IP address should be matched against. 0 means ignore, 255 means match.
  31. * @return {Boolean}
  32. */
  33. function isInNet (host, pattern, mask, fn) {
  34. var family = 4;
  35. dns.lookup(host, family, function (err, ip) {
  36. if (err) return fn(err);
  37. if (!ip) ip = '127.0.0.1';
  38. var netmask = new Netmask(pattern, mask);
  39. fn(null, netmask.contains(ip));
  40. });
  41. }