Skip to content

Instantly share code, notes, and snippets.

@thosil
Created July 31, 2019 13:46
Show Gist options
  • Select an option

  • Save thosil/672b088741413e525da2b99eb2e9605c to your computer and use it in GitHub Desktop.

Select an option

Save thosil/672b088741413e525da2b99eb2e9605c to your computer and use it in GitHub Desktop.
Node.js get default interface (not tested with multiple ip on the same interface)
#!/usr/bin/env node
const os = require("os");
const util = require("util");
const fs = require("fs");
const readFile = util.promisify(fs.readFile);
readFile("/proc/net/route")
.then(body => {
const intf = body.toString()
.split("\n")
.splice(1) // bypass header
.find( l => parseInt(l.split("\t")[3],16) & 0x2 === 0x2) // compare Flags field with 0x2, 0x2 means default gateway
.split("\t")[0]; // return interface name
const intfDetails = os.networkInterfaces()[intf]
.find(details => details.family === "IPv4")
console.log(`${intf}: ${intfDetails.cidr}`);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment