How to get ip client using express 4.x

I want to get the IP address of the client, and I'm trying to use localhost (127.0.0.1 ) , but I always get :: 1

I'm trying to use

 app.enable('trust proxy'); app.set('trust proxy', 'loopback'); app.get('/',function(req,res){ res.send(req.ip); //I always get :: 1 // or var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; res.send(ip);//I always get :: 1 }); 

how to get 127.0.0.1 , not :: 1 . It can be done?

+7
express
source share
2 answers

::1 is the equivalent of IPv6 localhost . If you want your server to listen on IPv4, and therefore you only have IPv4 addresses from your clients, you can specify the IPv4 address in app.listen() :

 app.listen(3000, '127.0.0.1'); 
+16
source share

Getting the IP address of clients is pretty simple in NodeJS:

  var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; console.log(ip); 
+3
source share

All Articles