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

Dung Do Tien Jul 02 2021 1178

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

    I hope it helpful for you!

  • T

    Teravut Anansiripinyo Jul 02 2021

    The following solution works for me:

      const clientIp = Object.values(require("os").networkInterfaces())
            .filter((item) => !item.internal && === "IPv4")

    Nice code!!!

  • 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");

    It's so short and easy.

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