10

I want to get the client's IP and I 'm trying with localhost (127.0.0.1 ) but I always get :: 1

i 'm trying using

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 can get 127.0.0.1 and not :: 1 . this can be done?

Julio Seña
  • 261
  • 1
  • 3
  • 10

2 Answers2

20

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

app.listen(3000, '127.0.0.1');
Trott
  • 66,479
  • 23
  • 173
  • 212
3

Getting the clients IP address is pretty straightforward in NodeJS:

 var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     req.connection.socket.remoteAddress;
 console.log(ip);
silverlight513
  • 5,268
  • 4
  • 26
  • 38
Garistar
  • 363
  • 3
  • 8
  • 1
    Beware! This doesn't answer the question and `x-forwarded-for` might lead you to spoofed results. Do NOT copy-paste until you have read over http://stackoverflow.com/a/19524949/2013580 and its comments. – zurfyx Jan 25 '17 at 08:42