Reputation: 335
how we get ip address from node.js I'm try many way but it's doesn't work and return ::ffff:127.0.0.1 please give me some advice
This is my code:
app.put('/update-user-info', function(req, res){
// it's doesn't work and return ::ffff:127.0.0.1
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
});
Upvotes: 4
Views: 18843
Reputation: 311
Have you tried req.ip
?
req.ip
Contains the remote IP address of the request.
When the trust proxy setting does not evaluate to false, the value of this property is derived from the left-most entry in the X-Forwarded-For header. This header can be set by the client or by the proxy.
The req.ip and req.ips values are populated with the list of addresses from X-Forwarded-For
See Express 4.x API (About req.ip)
In case you are working with proxy, it requires a special application settings called trust_proxy
(default is false)
NOTE: X-Forwarded-* headers are easily spoofed and the detected IP addresses are unreliable.
See Options for 'trust proxy' setting and Express behind proxies for more information
Upvotes: 10
Reputation: 1231
As GuroKing said, I am going to add one more point to it.
Add app.set('trust proxy', true)
In nginx.conf file:
proxy_set_header X-Real-IP $remote_addr;
Upvotes: 4