Created
June 3, 2014 15:16
-
-
Save mlms13/67696210ce621dd10152 to your computer and use it in GitHub Desktop.
Find IP address in node
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
var getIpAddress = function (interfaces) { | |
'use strict'; | |
var ip = [], | |
iface = null; | |
// loop through each interface in the interfaces object | |
for (iface in interfaces) { | |
// loop through each of the objects in the iface array | |
interfaces[iface].forEach(function (i) { | |
// only keep track of non-internal IPv4 addresses | |
if(i.family === 'IPv4' && !i.internal) { | |
ip.push(i); | |
} | |
}); | |
} | |
// warn if multiple matches were found | |
if (ip.length > 1) { | |
console.warn('Multiple IP addresses found. Returning only the first one.'); | |
} | |
return ip[0].address; | |
}; | |
// usage | |
getIpAddress(require('os').networkInterfaces()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment