1 | import {networkInterfaces} from 'node:os';
|
2 | import defaultGateway from 'default-gateway';
|
3 | import ip from 'ipaddr.js';
|
4 |
|
5 | function findIp(gateway) {
|
6 | const gatewayIp = ip.parse(gateway);
|
7 |
|
8 |
|
9 | for (const addresses of Object.values(networkInterfaces())) {
|
10 | for (const {cidr} of addresses) {
|
11 | const net = ip.parseCIDR(cidr);
|
12 |
|
13 |
|
14 | if (net[0] && net[0].kind() === gatewayIp.kind() && gatewayIp.match(net)) {
|
15 | return net[0].toString();
|
16 | }
|
17 | }
|
18 | }
|
19 | }
|
20 |
|
21 | async function async(family) {
|
22 | try {
|
23 | const {gateway} = await defaultGateway[family]();
|
24 | return findIp(gateway);
|
25 | } catch {}
|
26 | }
|
27 |
|
28 | function sync(family) {
|
29 | try {
|
30 | const {gateway} = defaultGateway[family].sync();
|
31 | return findIp(gateway);
|
32 | } catch {}
|
33 | }
|
34 |
|
35 | export async function internalIpV6() {
|
36 | return async('v6');
|
37 | }
|
38 |
|
39 | export async function internalIpV4() {
|
40 | return async('v4');
|
41 | }
|
42 |
|
43 | export function internalIpV6Sync() {
|
44 | return sync('v6');
|
45 | }
|
46 |
|
47 | export function internalIpV4Sync() {
|
48 | return sync('v4');
|
49 | }
|