How can I get local IP address in Node.js server?

Dung Do Tien Jul 02 2021 306

I have a simple Node.js program running on my machine and now I want to get the local IP address of visitors who are using my program. How do I get it with Node.js?

My node version: 12.18.3.

Thanks for any suggestions.

Have 3 answer(s) found.
  • R

    Raja T Jul 02 2021

    You can create a common method to help get client IP anywhere in your Node program. You can code that function as below:

    '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
            if (net.family === 'IPv4' && !net.internal) {
                if (!results[name]) {
                    results[name] = [];
                }
                results[name].push(net.address);
            }
        }
    }
     // Client IP is: results["en0"][0]
    "172.189.0.009"

    I hope it helpful for you!

  • H

    Hoàng Nhật Duy Nguyễn Jul 02 2021

    It's very simple, You only install a module called ip like:

    npm install ip

    Then use this code as below:

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

    It's so short and easy.

  • T

    Teravut Anansiripinyo Jul 02 2021

    The following solution works for me:

     const clientIp = Object.values(require("os").networkInterfaces())
            .flat()
            .filter((item) => !item.internal && item.family === "IPv4")
            .find(Boolean).address;

    Nice code!!!

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close