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);
@bluefangs
Copy link

bluefangs commented Apr 6, 2018

I hate to be the condense-code combobreaker, but I have a question. Suppose there are a few interfaces and some of them have IP addresses assigned to them, how do I extract the IP of the currently connected interface?

As an example, I have the below interfaces: wlx20e01600b682, vmnet1, vmnet2, etc.

wlx20e01600b682 looks like:

 { address: '192.168.1.70',
    netmask: '255.255.255.0',
    family: 'IPv4',
    mac: '20:e0:16:00:b6:82',
    internal: false } 


Now, my desktop is actually connected to wlx20e01600b682. In the above approaches, I either get an array of all IPs or the first IP in the addresses array. Which sometimes is not the IP of the currently active interface. Is there a possibility to get that?

Something like how the npm 'ip' module does.

var ip = require('ip');
console.log(ip.address());

@tjbenton
Copy link

tjbenton commented Apr 29, 2020

I know this is an older gist but if you just use find it's shorter and faster because it doesn't go through all the items in the array and you don't need a the second function pop

import { networkInterfaces } from 'os'

const getLocalExternalIP = () => [].concat(...Object.values(networkInterfaces()))
  .find((details) => details.family === 'IPv4' && !details.internal)
  .address

@brokenthorn
Copy link

brokenthorn commented May 5, 2020

My TypeScript version of the functions to get internal and external IPv4 network interface infos (NInfos):

// commonjs: const { networkInterfaces } = require('os')
import { networkInterfaces, NetworkInterfaceInfo } from 'os';

/**
 * Returns an array of `NetworkInterfaceInfo`s for all host interfaces that
 * have IPv4 addresses from the private address space,
 * including the loopback address space (127.x.x.x).
 */
export const getPrivateIPNInfos = (): (NetworkInterfaceInfo | undefined)[] => {
  return Object.values(networkInterfaces())
    .flatMap((infos) => {
      return infos?.filter((i) => i.family === 'IPv4');
    })
    .filter((info) => {
      return (
        info?.address.match(
          /(^127\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)/
        ) !== null
      );
    });
};

/**
 * Returns an array of IPv4 addresses for all host interfaces that
 * have IPv4 addresses from the private address space,
 * including the loopback address space (127.x.x.x).
 */
export const getPrivateIPs = (): (string | undefined)[] => {
  return getPrivateIPNInfos().map((i) => i?.address);
};


/**
 * Returns an array of `NetworkInterfaceInfo`s for all host interfaces that
 * have IPv4 addresses from the external private address space,
 * ie. except the loopback (internal) address space (127.x.x.x).
 */
export const getPrivateExternalIPNInfos = (): (
  | NetworkInterfaceInfo
  | undefined
)[] => {
  return Object.values(networkInterfaces())
    .flatMap((infos) => {
      return infos?.filter((i) => !i.internal && i.family === 'IPv4');
    })
    .filter((info) => {
      return (
        info?.address.match(
          /(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)/
        ) !== null
      );
    });
};

/**
 * Returns an array of IPv4 addresses for all host interfaces that
 * have IPv4 addresses from the external private address space,
 * ie. except the loopback (internal) address space (127.x.x.x).
 */
export const getPrivateExternalIPs = (): (string | undefined)[] => {
  return getPrivateExternalIPNInfos().map((i) => i?.address);
};

Sample output:

[
  {
    address: '127.0.0.1',
    netmask: '255.0.0.0',
    family: 'IPv4',
    mac: '00:00:00:00:00:00',
    internal: true,
    cidr: '127.0.0.1/8'
  }
]
[
  {
    address: '192.168.88.176',
    netmask: '255.255.255.0',
    family: 'IPv4',
    mac: 'xx:xx:xx:xx:xx:xx',
    internal: false,
    cidr: '192.168.88.176/24'
  }
]

The other functions just return the addresses directly.

...Oh, yeah, the naming of the functions happened by accident, but I decided to keep them.

@hum-n
Copy link

hum-n commented Jan 31, 2021

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;

@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