Created
March 25, 2014 10:46
-
-
Save bendman/9759087 to your computer and use it in GitHub Desktop.
In Node.js, get the external IP address of the host machine.
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 getExternalIp() { | |
var ifconfig = require('os').networkInterfaces(); | |
var device, i, I, protocol; | |
for (device in ifconfig) { | |
// ignore network loopback interface | |
if (device.indexOf('lo') !== -1 || !ifconfig.hasOwnProperty(device)) { | |
continue; | |
} | |
for (i=0, I=ifconfig[device].length; i<I; i++) { | |
protocol = ifconfig[device][i]; | |
// filter for external IPv4 addresses | |
if (protocol.family === 'IPv4' && protocol.internal === false) { | |
console.log('found', protocol.address); | |
return protocol.address; | |
} | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This snippet won't work all the time. Take a look:
So the output will be "found 192.168.1.3"