简体   繁体   中英

public ip npm package not working in Digital Ocean server

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.

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}`); // eg 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); }); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM