UNPKG

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