Created
July 31, 2019 13:46
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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