Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

index.js 1.1 KiB

3 anos atrás
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 (err) {
  32. return null;
  33. }
  34. }
  35. module.exports.v6 = () => promise('v6');
  36. module.exports.v4 = () => promise('v4');
  37. module.exports.v6.sync = () => sync('v6');
  38. module.exports.v4.sync = () => sync('v4');