Skip to content

Instantly share code, notes, and snippets.

@Marak
Created August 6, 2012 11:43
Show Gist options
  • Save Marak/3273796 to your computer and use it in GitHub Desktop.
Save Marak/3273796 to your computer and use it in GitHub Desktop.
A terrible solution for finding network gateway
//
// Since the code to actually figure this out doesn't exist in node yet
//
// see: https://groups.google.com/forum/?fromgroups#!topic/nodejs-dev/QbcnxS0_yyg
//
var guessGateway = function () {
var network = os.networkInterfaces(),
guess = '10.0.0.1';
Object.keys(network).forEach(function(interfaces){
network[interfaces].forEach(function(interface){
if(!interface.internal && interface.family === "IPv4") {
guess = interface.address.split('.');
guess[guess.length -1] = "1";
guess = guess.join('.');
}
});
})
return guess;
};
@aadamowski
Copy link

A more correct solution would be to expose the system routing table in the Node.JS API and then:

var routes = os.networkRoutes(),
    guess = '10.0.0.1';
Object.keys(routes).forEach(function(route){
  if (route.default && route.proto === 'IPv4' && typeof route.gateway !== 'undefined') {
    guess = route.gateway;
  }
});

@Marak
Copy link
Author

Marak commented Aug 6, 2012

No, that is stupid. Read the link in the code comments.

@aadamowski
Copy link

Oh, I've been sorta Node.JS rickrolled.

@joshaven
Copy link

joshaven commented Aug 6, 2012

How about using the traceroute and awk commands from Linux/Unix...

var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }

exec("traceroute -m1 -n 8.8.8.8|awk '{print $2}'", puts);

@Marak
Copy link
Author

Marak commented Aug 6, 2012

I'm starting a countdown until @indutny lands the module that does this.

I think he can do it in < 1 week.

Maybe < 1 day if he's motivated.

@roccomuso
Copy link

What's the best way nowadays to find the gateway's IP Address in Node?

@akrv
Copy link

akrv commented Jan 31, 2017

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment