選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

48 行
1.1 KiB

  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');