UNPKG

2.82 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.findLoopbackAddress = findLoopbackAddress;
4exports.getOSLoopbackAddress = getOSLoopbackAddress;
5exports.getOSLoopbackAddressIfAvailable = getOSLoopbackAddressIfAvailable;
6const tslib_1 = require("tslib");
7const os_1 = tslib_1.__importDefault(require("os"));
8/**
9 * @group Utils
10 */
11function findLoopbackAddress() {
12 let ipv6 = undefined; // ::1/128
13 let ipv6LinkLocal = undefined; // fe80::/10
14 let ipv4 = undefined; // 127.0.0.1/8
15 for (const [name, infos] of Object.entries(os_1.default.networkInterfaces())) {
16 let internal = false;
17 if (infos) {
18 for (const info of infos) {
19 if (!info.internal) {
20 continue;
21 }
22 internal = true;
23 // @ts-expect-error Nodejs 18+ uses the number 4 the string "IPv4"
24 if (info.family === "IPv4" || info.family === 4) {
25 if (!ipv4) {
26 ipv4 = info.address;
27 }
28 // @ts-expect-error Nodejs 18+ uses the number 6 the string "IPv6"
29 }
30 else if (info.family === "IPv6" || info.family === 6) {
31 if (info.scopeid) {
32 if (!ipv6LinkLocal) {
33 ipv6LinkLocal = info.address + "%" + name; // ipv6 link local addresses are only valid with a scope
34 }
35 }
36 else if (!ipv6) {
37 ipv6 = info.address;
38 }
39 }
40 }
41 }
42 if (internal) {
43 break;
44 }
45 }
46 const address = ipv4 || ipv6 || ipv6LinkLocal;
47 if (!address) {
48 throw new Error("Could not find a valid loopback address on the platform!");
49 }
50 return address;
51}
52let loopbackAddress = undefined; // loopback addressed used for the internal http server (::1 or 127.0.0.1)
53/**
54 * Returns the loopback address for the machine.
55 * Uses IPV4 loopback address by default and falls back to global unique IPv6 loopback and then
56 * link local IPv6 loopback address.
57 * If no loopback interface could be found a error is thrown.
58 *
59 * @group Utils
60 */
61function getOSLoopbackAddress() {
62 return loopbackAddress ?? (loopbackAddress = findLoopbackAddress());
63}
64/**
65 * Refer to {@link getOSLoopbackAddress}.
66 * Instead of throwing an error, undefined is returned if loopback interface couldn't be detected.
67 *
68 * @group Utils
69 */
70function getOSLoopbackAddressIfAvailable() {
71 try {
72 return loopbackAddress ?? (loopbackAddress = findLoopbackAddress());
73 }
74 catch (error) {
75 console.log(error.stack);
76 return undefined;
77 }
78}
79//# sourceMappingURL=net-utils.js.map
\No newline at end of file