Created
December 27, 2013 03:39
-
-
Save jhurliman/8142283 to your computer and use it in GitHub Desktop.
Make a best guess at the IP address for the local machine, preferring the first non-loopback non-internal IPv4 address.
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
function getIP() { | |
var interfaces = require('os').networkInterfaces(); | |
var names = Object.keys(interfaces); | |
var addresses = []; | |
var idx = 0; | |
for (var i = 0; i < names.length; i++) { | |
var name = names[i]; | |
var nic = interfaces[name]; | |
for (var j = 0; j < nic.length; j++) { | |
var address = nic[j]; | |
address.lo = name.indexOf('lo') === 0; | |
address.ipv4 = address.family.toLowerCase() === 'ipv4'; | |
address.idx = idx++; | |
addresses.push(address); | |
} | |
} | |
addresses.sort(function(a, b) { | |
if (a.lo && !b.lo) return 1; | |
else if (!a.lo && b.lo) return -1; | |
if (a.internal && !b.internal) return 1; | |
else if (!a.internal && b.internal) return -1; | |
if (a.ipv4 && !b.ipv4) return -1; | |
else if (!a.ipv4 && b.ipv4) return 1; | |
return a.idx - b.idx; | |
}); | |
return addresses.length ? addresses[0].address : '127.0.0.1'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment