Skip to content

Instantly share code, notes, and snippets.

@bendman
Created March 25, 2014 10:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bendman/9759087 to your computer and use it in GitHub Desktop.
Save bendman/9759087 to your computer and use it in GitHub Desktop.
In Node.js, get the external IP address of the host machine.
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;
}
@ecdeveloper
Copy link

This snippet won't work all the time. Take a look:

> os.networkInterfaces()
{ lo0: 
   [ { address: '::1',
       family: 'IPv6',
       internal: true },
     { address: '127.0.0.1',
       family: 'IPv4',
       internal: true },
     { address: 'fe80::1',
       family: 'IPv6',
       internal: true } ],
  en0: 
   [ { address: 'fe80::82e6:50ff:fe05:a19e',
       family: 'IPv6',
       internal: false },
     { address: '192.168.1.3',
       family: 'IPv4',
       internal: false } ],
  vboxnet0: 
   [ { address: '192.168.33.1',
       family: 'IPv4',
       internal: false } ] }

So the output will be "found 192.168.1.3"

@tobiasoberrauch
Copy link

Some providers switched to IPv6.
I solved it by using a tunnel (https://github.com/localtunnel/)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment