index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const os = require('os');
  3. const defaultGateway = require('default-gateway');
  4. const ipaddr = require('ipaddr.js');
  5. function findIp(gateway) {
  6. const interfaces = os.networkInterfaces();
  7. const gatewayIp = ipaddr.parse(gateway);
  8. let ip;
  9. // Look for the matching interface in all local interfaces
  10. Object.keys(interfaces).some(name => {
  11. return interfaces[name].some(addr => {
  12. const prefix = ipaddr.parse(addr.netmask).prefixLengthFromSubnetMask();
  13. const net = ipaddr.parseCIDR(`${addr.address}/${prefix}`);
  14. if (net[0] && net[0].kind() === gatewayIp.kind() && gatewayIp.match(net)) {
  15. ip = net[0].toString();
  16. }
  17. return Boolean(ip);
  18. });
  19. });
  20. return ip;
  21. }
  22. function promise(family) {
  23. return defaultGateway[family]().then(result => {
  24. return findIp(result.gateway) || null;
  25. }).catch(() => null);
  26. }
  27. function sync(family) {
  28. try {
  29. const result = defaultGateway[family].sync();
  30. return findIp(result.gateway) || null;
  31. } catch (error) {
  32. return null;
  33. }
  34. }
  35. const internalIp = {};
  36. internalIp.v6 = () => promise('v6');
  37. internalIp.v4 = () => promise('v4');
  38. internalIp.v6.sync = () => sync('v6');
  39. internalIp.v4.sync = () => sync('v4');
  40. module.exports = internalIp;
  41. // TODO: Remove this for the next major release
  42. module.exports.default = internalIp;