Projekt

Obecné

Profil

Stáhnout (1.26 KB) Statistiky
| Větev: | Revize:
1 3a515b92 cagy
'use strict';
2
const os = require('os');
3
const defaultGateway = require('default-gateway');
4
const ipaddr = require('ipaddr.js');
5
6
function findIp(gateway) {
7
	const interfaces = os.networkInterfaces();
8
	const gatewayIp = ipaddr.parse(gateway);
9
	let ip;
10
11
	// Look for the matching interface in all local interfaces
12
	Object.keys(interfaces).some(name => {
13
		return interfaces[name].some(addr => {
14
			const prefix = ipaddr.parse(addr.netmask).prefixLengthFromSubnetMask();
15
			const net = ipaddr.parseCIDR(`${addr.address}/${prefix}`);
16
17
			if (net[0] && net[0].kind() === gatewayIp.kind() && gatewayIp.match(net)) {
18
				ip = net[0].toString();
19
			}
20
21
			return Boolean(ip);
22
		});
23
	});
24
25
	return ip;
26
}
27
28
function promise(family) {
29
	return defaultGateway[family]().then(result => {
30
		return findIp(result.gateway) || null;
31
	}).catch(() => null);
32
}
33
34
function sync(family) {
35
	try {
36
		const result = defaultGateway[family].sync();
37
		return findIp(result.gateway) || null;
38
	} catch (error) {
39
		return null;
40
	}
41
}
42
43
const internalIp = {};
44
internalIp.v6 = () => promise('v6');
45
internalIp.v4 = () => promise('v4');
46
internalIp.v6.sync = () => sync('v6');
47
internalIp.v4.sync = () => sync('v4');
48
49
module.exports = internalIp;
50
// TODO: Remove this for the next major release
51
module.exports.default = internalIp;