Files
cloudron-box/src/sysinfo/network-interface.js

52 lines
1.9 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
getServerIPv4,
getServerIPv6,
2019-10-29 20:08:45 -07:00
testConfig
};
const assert = require('assert'),
BoxError = require('../boxerror.js'),
2019-10-29 20:33:32 -07:00
debug = require('debug')('box:sysinfo/network-interface'),
os = require('os'),
safe = require('safetydance');
async function getServerIPv4(config) {
assert.strictEqual(typeof config, 'object');
const ifaces = os.networkInterfaces();
const iface = ifaces[config.ifname]; // array of addresses
if (!iface) throw new BoxError(BoxError.NETWORK_ERROR, `No interface named ${config.ifname}`);
const addresses = iface.filter(i => i.family === 'IPv4').map(i => i.address);
if (addresses.length === 0) throw new BoxError(BoxError.NETWORK_ERROR, `${config.ifname} does not have any IPv4 address`);
if (addresses.length > 1) debug(`${config.ifname} has multiple ipv4 - ${JSON.stringify(addresses)}. choosing the first one.`);
return addresses[0];
}
2019-10-29 20:08:45 -07:00
async function getServerIPv6(config) {
assert.strictEqual(typeof config, 'object');
const ifaces = os.networkInterfaces();
const iface = ifaces[config.ifname]; // array of addresses
if (!iface) throw new BoxError(BoxError.NETWORK_ERROR, `No interface named ${config.ifname}`);
const addresses = iface.filter(i => i.family === 'IPv6').map(i => i.address);
2022-01-06 12:22:16 -08:00
if (addresses.length === 0) throw new BoxError(BoxError.NETWORK_ERROR, `${config.ifname} does not have any IPv6 address`);
if (addresses.length > 1) debug(`${config.ifname} has multiple ipv6 - ${JSON.stringify(addresses)}. choosing the first one.`);
return addresses[0];
}
async function testConfig(config) {
2019-10-29 20:08:45 -07:00
assert.strictEqual(typeof config, 'object');
assert.strictEqual(typeof callback, 'function');
if (typeof config.ifname !== 'string') return new BoxError(BoxError.BAD_FIELD, 'ifname is not a string');
2019-11-05 15:03:36 +01:00
const [error] = await safe(getServerIPv4(config));
return error || null;
2019-10-29 20:08:45 -07:00
}