Skip to content

Instantly share code, notes, and snippets.

@szalishchuk
Last active December 14, 2022 11:04
Show Gist options
  • Save szalishchuk/9054346 to your computer and use it in GitHub Desktop.
Save szalishchuk/9054346 to your computer and use it in GitHub Desktop.
Get local external ip address with nodejs
var
// Local ip address that we're trying to calculate
address
// Provides a few basic operating-system related utility functions (built-in)
,os = require('os')
// Network interfaces
,ifaces = os.networkInterfaces();
// Iterate over interfaces ...
for (var dev in ifaces) {
// ... and find the one that matches the criteria
var iface = ifaces[dev].filter(function(details) {
return details.family === 'IPv4' && details.internal === false;
});
if(iface.length > 0) address = iface[0].address;
}
// Print the result
console.log(address);
@click2cloud-rajat
Copy link

Thanks, it worked !! Optimized it further as:

const ip = Object.values(require('os').networkInterfaces()).flat().find(i => i.family == 'IPv4' && !i.internal).address;

@brokenthorn
Copy link

Thanks, it worked !! Optimized it further as:

const ip = Object.values(require('os').networkInterfaces()).flat().find(i => i.family == 'IPv4' && !i.internal).address;

I'm sorry Rajat but making code less readable is not an optimization. 😉

@katsimoto
Copy link

Even more condensed with find and flat.

import { networkInterfaces } from 'os';

const ip = Object.values(networkInterfaces()).flat().find(i => i.family == 'IPv4' && !i.internal).address;

Typescript version (added optional chaining):

import { networkInterfaces } from 'os';

const ip = Object.values(networkInterfaces()).flat().find((i) => i?.family === 'IPv4' && !i?.internal)?.address;

@FriendlyNGeeks
Copy link

thank all of you so much

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