Socket
Socket
Sign inDemoInstall

default-gateway

Package Overview
Dependencies
Maintainers
1
Versions
54
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

default-gateway - npm Package Compare versions

Comparing version 0.8.6 to 1.0.0

18

index.js
"use strict";
const os = require("os");
const platform = require("os").platform();
module.exports = cb => {
const platform = os.platform();
if (/^linux|darwin|win32$/.test(platform)) {
return require("./" + platform)(cb);
} else {
throw new Error("Unsupported Platform: " + platform);
}
};
if (/^linux|darwin|win32/.test(platform)) {
module.exports.v4 = () => require("./" + platform).v4();
module.exports.v6 = () => require("./" + platform).v6();
} else {
module.exports.v4 = () => { throw new Error("Unsupported Platform: " + platform); };
module.exports.v6 = () => { throw new Error("Unsupported Platform: " + platform); };
}
{
"name": "default-gateway",
"version": "0.8.6",
"description": "A Node.js module to get default gateway and default interface.",
"version": "1.0.0",
"description": "Get the default network gateway, cross-platform.",
"author": "silverwind <me@silverwind.io>",
"repository": "silverwind/default-gateway",
"license": "BSD-2-Clause",
"scripts": {
"test": "make test"
},
"engines": {
"node": ">=4"
},
"dependencies": {
"ip-regex": "^2.1.0"
},
"os": [

@@ -17,30 +24,13 @@ "win32",

"index.js",
"darwin.js",
"linux.js",
"unix.js",
"win32.js"
],
"keywords": [
"win32",
"darwin",
"linux",
"net",
"default gateway",
"network",
"default",
"gateway",
"child_process",
"wmi",
"routing",
"route"
],
"license": "MIT",
"dependencies": {
"async": "2.4.1",
"xml2js": "^0.4.17"
},
"devDependencies": {
"chai": "4.0.2",
"mocha": "3.4.2",
"mocha-clean": "1.0.0"
},
"engines": {
"node": ">=4"
}
]
}
# default-gateway
[![](https://img.shields.io/npm/v/default-gateway.svg?style=flat)](https://www.npmjs.org/package/default-gateway) [![](https://img.shields.io/npm/dm/default-gateway.svg)](https://www.npmjs.org/package/default-gateway) [![](https://api.travis-ci.org/silverwind/default-gateway.svg?style=flat)](https://travis-ci.org/silverwind/default-gateway)
> Get the default network gateway and the default interface.
> Get the default network gateway, cross-platform.
This module is based on [previous work](https://github.com/mh61503891/node-default-network) from [@mh61503891](https://github.com/mh61503891).
Obtains the network gateway through `exec` calls to OS routing interfaces. Supports Linux, macOS and Windows.
## Installation
```bash
npm install --save default-gateway
```
## API
### defaultGateway(callback)
Asynchronously collects a object which contains interface names, families (IPv4 or IPv6), and addresses. The `callback` gets two arguments `(error, data)`.
#### Example 1 - Get default gateway and default interface
$ npm install --save default-gateway
```
## Example
```js
const defaultGateway = require('default-gateway');
defaultGateway((error, data) => {
console.log(data);
// { en4:
// [ { family: 'IPv4', address: '192.168.1.1' },
// { family: 'IPv6', address: 'fe80::20b:a2ff:fede:2886%en4' } ],
// en0:
// [ { family: 'IPv4', address: '192.168.1.1' },
// { family: 'IPv6', address: 'fe80::20b:a2ff:fede:2886%en0' } ],
// en8:
// [ { family: 'IPv4', address: '192.168.1.1' },
// { family: 'IPv6', address: 'fe80::20b:a2ff:fede:2886%en8' } ]
// }
defaultGateway.v4().then(result => {
//=> {gateway: '1.2.3.4', interface: 'en1'}
});
```
#### Example 2 - Get default interface from `os.networkInterfaces()`.
```js
const os = require('os');
const defaultGateway = require('default-gateway');
defaultGateway((error, data) => {
const names = Object.keys(data); // names[0] is 'en4'
console.log(os.networkInterfaces()[names[0]]);
// [
// { address: 'fe80::6a5b:35ff:fe96:cc05',
// netmask: 'ffff:ffff:ffff:ffff::',
// family: 'IPv6',
// mac: '00:00:00:00:00:00',
// scopeid: 14,
// internal: false },
// { address: '2001:a0ae:7c22:0:6a5b:35ff:fe96:cc05',
// netmask: 'ffff:ffff:ffff:ffff::',
// family: 'IPv6',
// mac: '00:00:00:00:00:00',
// scopeid: 0,
// internal: false },
// { address: '2001:a0ae:7c22:0:a8d1:fef3:2917:cd87',
// netmask: 'ffff:ffff:ffff:ffff::',
// family: 'IPv6',
// mac: '00:00:00:00:00:00',
// scopeid: 0,
// internal: false },
// { address: '192.168.1.10',
// netmask: '255.255.255.0',
// family: 'IPv4',
// mac: '00:00:00:00:00:00',
// internal: false }
// ]
defaultGateway.v6().then(result => {
//=> {gateway: '2001:db8::1', interface: 'en2'}
});
```
## How it works
## API
### default-gateway.v4()
This module depends on following commands by using [child_process](https://nodejs.org/api/child_process.html):
Returns a promise that resolves to a object containing the IPv4 `gateway` and `interface`. If it succeeds, `gateway` will always be defined, while `interface` can be absent. Rejects when the gateway cannot be determined.
- win32
- `wmic path Win32_NetworkAdapterConfiguration get *`
- `wmic path Win32_NetworkAdapter get *`
- darwin
- `netstat -rn -f inet`
- `netstat -rn -f inet6`
- linux
- `netstat -rn -A inet`
- `netstat -rn -A inet6`
### default-gateway.v6()
## License
Returns a promise that resolves to a object containing the IPv6 `gateway` and `interface`. If it succeeds, `gateway` will always be defined, while `interface` can be absent. Rejects when the gateway cannot be determined.
The MIT License
© [silverwind](https://github.com/silverwind), distributed under BSD licence

@@ -1,118 +0,36 @@

const net = require("net");
const {exec} = require("child_process");
const async = require("async");
const parseXML = require("xml2js").parseString;
"use strict";
const wmic = function(cls, keys, callback) {
const command = `wmic path ${cls} get ${keys.join(",")} /format:rawxml`;
return exec(command, function(error, stdout) {
if (error !== null) { return callback(error); }
return parseXML(stdout, {
trim: true,
normalize: true,
normalizeTags: true,
mergeAttrs: true,
async: true
}, function(error, result) {
const records = [];
for (const r of Array.from(result.command.results[0].cim[0].instance)) {
const record = {};
for (const p of Array.from(r.property || [])) {
record[p.NAME] = (p.value && p.value[0]) || "";
}
for (const p of Array.from(r["property.array"] || [])) {
const val = p["value.array"];
record[p.NAME] = (val && p["value.array"][0].value) || "";
}
records.push(record);
}
return callback(error, records);
});
});
};
const exec = require("child_process").exec;
const ipRegex = require("ip-regex");
const getAdapterConfig = callback => {
wmic("Win32_NetworkAdapterConfiguration",
["Index", "IPEnabled", "DefaultIPGateway"],
(error, records) => callback(error, records));
};
const getAdapter = callback => {
wmic("Win32_NetworkAdapter",
["Index", "NetConnectionID"],
(error, records) => callback(error, records));
};
const getDefaultGateway = callback => {
getAdapterConfig(function(error, records) {
if (error !== null) { return callback(error); }
const data = {};
for (const record of Array.from(records)) {
if ((record["IPEnabled"] === null)) return;
if ((record["DefaultIPGateway"] === null)) return;
if ((record["Index"] === null)) return;
if (record["IPEnabled"] !== "TRUE") return;
if (record["DefaultIPGateway"].length === 0) return;
if (isNaN(parseInt(record["Index"]))) return;
const index = record["Index"];
const defaultGateway = record["DefaultIPGateway"];
for (const address of Array.from(defaultGateway)) {
switch (net.isIP(address)) {
case 4:
data[index] = data[index] || [];
data[index].push({family: "IPv4", address});
break;
case 6:
data[index] = data[index] || [];
data[index].push({family: "IPv6", address});
break;
default:
return callback(new Error(`${address} is not IP address`));
}
}
}
return callback(null, data);
});
};
const getAdapterNameByIndex = (index, callback) => {
getAdapter(function(error, records) {
if (error !== null) { return callback(error); }
for (const record of Array.from(records)) {
if (record["Index"] === index) {
return callback(null, record["NetConnectionID"]);
}
}
return callback(new Error(`inteface ${index} is not available`));
});
};
const getDefaultNetwork = callback => {
getDefaultGateway(function(error, gateways) {
if (error !== null) { return callback(error); }
const indexes = Object.keys(gateways);
return async.map(indexes,
(index, callback) =>
getAdapterNameByIndex(index, function(error, name) {
if (error !== null) { return callback(error); }
const iface = {index, name};
return callback(null, iface);
})
,
function(error, ifaces) {
if (error !== null) { return callback(error); }
const data = {};
for (const iface of Array.from(ifaces)) {
data[iface.name] = gateways[iface.index];
}
return callback(null, data);
function wmic(proto) {
return new Promise(function(resolve, reject) {
let gateway, gwid, iface;
exec("wmic path Win32_NetworkAdapterConfiguration where IPEnabled=true get DefaultIPGateway,Index /format:table", function(_, gwtable) {
exec("wmic path Win32_NetworkAdapter get Index,NetConnectionID /format:table", function(_, iftable) {
gwtable.trim().split("\n").splice(1).some(function(line) {
const [gw, id] = line.trim().split(/} +/);
gateway = (ipRegex[proto]().exec((gw || "").trim()) || [])[0];
if (gateway) {
gwid = id;
return true;
}
});
iftable.trim().split("\n").splice(1).some(function(line) {
const spaceIndex = line.indexOf(" ");
const id = line.substr(0, spaceIndex).trim();
const name = line.substr(spaceIndex + 1).trim();
if (id === gwid && name) {
iface = name;
resolve({gateway: gateway, interface: iface});
return true;
}
});
reject(new Error("Unable to determine default gateway"));
});
});
});
};
}
module.exports = callback => {
getDefaultNetwork(function(error, data) {
if (error !== null) { return callback(null, {}); }
return callback(null, data);
});
};
module.exports.v4 = () => wmic("v4");
module.exports.v6 = () => wmic("v6");

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc