Skip to content

Instantly share code, notes, and snippets.

@asciimo
Last active November 3, 2017 21:35
Show Gist options
  • Select an option

  • Save asciimo/cb31e9ac355a5f08a80ef85673a369ca to your computer and use it in GitHub Desktop.

Select an option

Save asciimo/cb31e9ac355a5f08a80ef85673a369ca to your computer and use it in GitHub Desktop.
Get the server's gateway ip address in a node script.
const util = require('util')
const execFile = util.promisify(require('child_process').execFile); // node 8+
const getGatewayIp = () =>
new Promise((resolve, reject) => {
execFile('/sbin/ip', ["route"])
.then(result => {
if (result.stdout) {
const ip_pattern = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/;
const ip = result.stdout.match(ip_pattern)[0];
resolve(ip);
}
if (result.stderr) {
console.log(`stderr: ${result.stderr}`);
reject(stderr);
}
})
.catch(e => reject(e));
})
getGatewayIp()
.then(result => console.log(`IP address is ${result}`))
.catch(e => console.log(`Exception: ${e}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment