Last active
December 14, 2022 11:04
-
-
Save szalishchuk/9054346 to your computer and use it in GitHub Desktop.
Get local external ip address with nodejs
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
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); |
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;
Thanks, it worked !! Optimized it further as:
const ip = Object.values(require('os').networkInterfaces()).flat().find(i => i.family == 'IPv4' && !i.internal).address;
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. 😉
Even more condensed with
find
andflat
.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;
thank all of you so much
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My TypeScript version of the functions to get internal and external IPv4 network interface infos (NInfos):
Sample output:
The other functions just return the addresses directly.
...Oh, yeah, the naming of the functions happened by accident, but I decided to keep them.