Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท path, os and url

Node.js os.networkInterfaces() method

Reference for os.networkInterfaces() in Node.js: list interface addresses, filter IPv4 and IPv6, find the loopback and skip internal entries.

os.networkInterfaces() returns an object that maps each network interface name (such as lo, eth0 or Wi-Fi) to an array of address records. Each record describes one assigned address with its netmask, MAC address and whether it is internal.

It is the tool for finding "my own IP address" or for printing a friendly "listening on" message. It reads the local configuration only; it never contacts the network.

NODE
import os from "node:os";

console.log(Object.keys(os.networkInterfaces()));

Try it

Node.js The loopback interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Filtering external IPv4 addresses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
os.networkInterfaces(): {
  [name: string]: Array<{
    address: string,
    netmask: string,
    family: "IPv4" | "IPv6",
    mac: string,
    internal: boolean,
    cidr: string | null,
    scopeid?: number   // IPv6 only
  }> | undefined
}
Name Description
(none) The function takes no arguments.

Returns: a plain object keyed by interface name. Values are arrays of records; address is the IP, netmask the mask, mac the hardware address, internal is true for loopback and similar, and cidr is the address with prefix length (for example 127.0.0.1/8).

Edge cases: an interface with no address can be missing or have an empty array, and a record's family is the string 'IPv4' or 'IPv6' in all current Node.js versions (some 18.x releases returned the numbers 4 and 6, so compare strings in new code but be prepared when supporting old runtimes).

Usage notes

  • Filter internal. Loopback addresses are not reachable from other machines.
  • Skip IPv6 link-local addresses (starting with fe80::) when you need something shareable; they need a scope ID.
  • Virtual interfaces are included. Docker, VPN and virtual machine adapters appear next to the real network card, so "the first address" is often the wrong one.
  • MAC 00:00:00:00:00:00 is reported for loopback and some virtual adapters. Do not use MAC addresses as unique identifiers.
  • A listening server that binds to 0.0.0.0 is reachable on every address from this list.
  • Snapshots only. Addresses can change (Wi-Fi roaming, VPN); call again if you need current data.