Last active
August 29, 2015 14:04
-
-
Save ChiChou/103286c0ceb099e022e5 to your computer and use it in GitHub Desktop.
Intranet IP detection for Node.js
This file contains 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
(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