0

I had a question, but how to get the IP address of the computer on which my application is running on Node.JS? Importantly, the IP address must not be local (127.0.0.1 or 192.168.1.1). Thank you in advance

  • This might be useful, https://www.ipify.org/ just do a http request to this website, and it will return you your public ip. – Keith Nov 24 '18 at 01:03
  • 5
    Possible duplicate of [How to get my external IP address with node.js?](https://stackoverflow.com/questions/20273128/how-to-get-my-external-ip-address-with-node-js) – James Ives Nov 24 '18 at 01:07
  • using req.headers['x-forwarded-for'] might help take a look at here https://stackoverflow.com/questions/10849687/express-js-how-to-get-remote-client-address – Shaahin Shemshian Nov 24 '18 at 05:53

1 Answers1

0

You can use os.networkInterfaces() to get all the IP address information and exclude the local addresses.

According to Node.js document:

The os.networkInterfaces() method returns an object containing only network interfaces that have been assigned a network address.

Each key on the returned object identifies a network interface. The associated value is an array of objects that each describe an assigned network address.

Here is a code example:

'use strict';

const os = require('os');

let networkInterfaces = os.networkInterfaces();

let nonLocalInterfaces = {};
for (let inet in networkInterfaces) {
  let addresses = networkInterfaces[inet];
  for (let i=0; i<addresses.length; i++) {
    let address = addresses[i];
    if (!address.internal) {
      if (!nonLocalInterfaces[inet]) {
        nonLocalInterfaces[inet] = [];
      }
      nonLocalInterfaces[inet].push(address);
    }
  }
}

console.log(nonLocalInterfaces);
Community
  • 1
  • 1
shaochuancs
  • 12,430
  • 3
  • 40
  • 51