javascriptnode.jsip

Get local IP address in Node.js


I have a simple Node.js program running on my machine and I want to get the local IP address of a PC on which my program is running. How do I get it with Node.js?


Solution

  • This information can be found in os.networkInterfaces(), — an object, that maps network interface names to its properties (so that one interface can, for example, have several addresses):

    'use strict';
    
    const { networkInterfaces } = require('os');
    
    const nets = networkInterfaces();
    const results = Object.create(null); // Or just '{}', an empty object
    
    for (const name of Object.keys(nets)) {
        for (const net of nets[name]) {
            // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
            // 'IPv4' is in Node <= 17, from 18 it's a number 4 or 6
            const familyV4Value = typeof net.family === 'string' ? 'IPv4' : 4
            if (net.family === familyV4Value && !net.internal) {
                if (!results[name]) {
                    results[name] = [];
                }
                results[name].push(net.address);
            }
        }
    }
    
    // 'results'
    {
      "en0": [
        "192.168.1.101"
      ],
      "eth0": [
        "10.0.0.101"
      ],
      "<network name>": [
        "<ip>",
        "<ip alias>",
        "<ip alias>",
        ...
      ]
    }
    
    // results["en0"][0]
    "192.168.1.101"