ip.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.ip = void 0;
  7. const os_1 = __importDefault(require("os"));
  8. exports.ip = {
  9. address() {
  10. const interfaces = os_1.default.networkInterfaces();
  11. // Default to `ipv4`
  12. const family = normalizeFamily();
  13. const all = Object.values(interfaces).map((addrs = []) => {
  14. const addresses = addrs.filter((details) => {
  15. const detailsFamily = normalizeFamily(details.family);
  16. if (detailsFamily !== family || exports.ip.isLoopback(details.address)) {
  17. return false;
  18. }
  19. return true;
  20. });
  21. return addresses.length ? addresses[0].address : undefined;
  22. }).filter(Boolean);
  23. return !all.length ? exports.ip.loopback(family) : all[0];
  24. },
  25. isLoopback(addr) {
  26. return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/
  27. .test(addr)
  28. || /^fe80::1$/.test(addr)
  29. || /^::1$/.test(addr)
  30. || /^::$/.test(addr);
  31. },
  32. loopback(family) {
  33. // Default to `ipv4`
  34. family = normalizeFamily(family);
  35. if (family !== 'ipv4' && family !== 'ipv6') {
  36. throw new Error('family must be ipv4 or ipv6');
  37. }
  38. return family === 'ipv4' ? '127.0.0.1' : 'fe80::1';
  39. }
  40. };
  41. function normalizeFamily(family) {
  42. if (family === 4) {
  43. return 'ipv4';
  44. }
  45. if (family === 6) {
  46. return 'ipv6';
  47. }
  48. return family ? family.toLowerCase() : 'ipv4';
  49. }
  50. //# sourceMappingURL=ip.js.map