Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how get ip client using express 4.x

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?

like image 239
Julio Seña Avatar asked May 26 '15 15:05

Julio Seña


People also ask

How do I find the client IP address?

To get the client's public IP address, JavaScript acts as a third-party server-side language. JavaScript can't do it alone, so, jQuery is added to do this. JavaScript works with third-party applications to fetch the IP addresses.

How do I find my IP address on Express?

Access the socket field of the Express request object, and then look up the remoteAddress property of that field. The remoteAddress will be the address of the client that sent the request. If you are running the app in development, this will be the loopback address: 127.0. 0.1 for IPv4 and ::1 for IPv6.


2 Answers

::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');
like image 64
Trott Avatar answered Nov 11 '22 22:11

Trott


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);
like image 28
Garistar Avatar answered Nov 11 '22 22:11

Garistar