0

I have used the public-ip npm package to get the public IP address of the user, it is giving the same public IP address as in http://whatismyipaddress.com, but when using it in a Digital Ocean server it is giving me the Digital Ocean IP address instead of user's public IP address.

I have tried it on nodejs.

const publicIp = require('public-ip');
const ip = await publicIp.v4(); //to save ip in user

I want the public IP address of the user instead of getting the Digital Ocean IP address.

Laurenz Albe
  • 129,316
  • 15
  • 96
  • 132
  • 1
    You don't need any module to get user ip. See https://stackoverflow.com/questions/8107856/how-to-determine-a-users-ip-address-in-node – Molda Jun 25 '19 at 10:28

2 Answers2

0

Just query https://api.ipify.org/

// web
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.ipify.org');
xhr.send();
xhr.onload = function() {
  if (xhr.status != 200) {
    console.log(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
  } else { // show the result
    console.log(xhr.response)
  }
};

// nodejs
const https = require('https');

https.get('https://api.ipify.org', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data));
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});
Medet Tleukabiluly
  • 9,929
  • 3
  • 30
  • 56
0

This function publicIp.v4() and public-ip module will help you get (detect) your public IP of server or computer that application's running on (not IP of user). And Digital Ocean returns value of its public IP is right.

In your case, you need to retrieve user's IP from user's request, it can be call remote client IP address. It's better for you to check this question Express.js: how to get remote client address

Hope it can help.

ThanhPhan
  • 1,167
  • 2
  • 10
  • 22
  • var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; This is returning ::1, why not ip? – Vishal Sinha Jun 27 '19 at 07:56
  • ::1 is equal localhost in IPv6 (means 127.0.0.1 in IPv4). Please check here: https://stackoverflow.com/questions/4611418/what-is-ip-address-1/4611421 – ThanhPhan Jun 27 '19 at 08:26
  • I am getting ::ffff:127.0.0.1 .How we can change to a ip, we get in whatismyipaddress.com? – Vishal Sinha Jun 27 '19 at 09:18