Skip to content

Instantly share code, notes, and snippets.

@ChiChou
Last active August 29, 2015 14:04
Show Gist options
  • Save ChiChou/103286c0ceb099e022e5 to your computer and use it in GitHub Desktop.
Save ChiChou/103286c0ceb099e022e5 to your computer and use it in GitHub Desktop.
Intranet IP detection for Node.js
(function() {
var os = require('os'), interfaces = os.networkInterfaces(),
ipFilter = function(addr) {
// no need to match 169.254.0.0/16
return !addr.internal &&
(addr.family === 'IPv4' && addr.address.match(/^(192|172|10)\./)) ||
(addr.family === 'IPv6' && addr.address.match(/^f(c0|e8)0:/) || addr.address.match(/^::1{0,1}$/));
};
for (var i in interfaces) {
// ignore interfaces created by vm
if (i.match(/^(VirtualBox|VMware)/)) {
continue;
}
var ip = interfaces[i].filter(ipFilter);
if (ip.length) {
// fetch the first one
// ip.pop() should work as well
return ip.shift().address;
}
}
// not found
return 'localhost';
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment