Obtain the client's IP in Node.js

3

I need to obtain the IP address of the person who consumes the API I am working with, this is the code I am using:

app.post('/api/v1',(req,res) =>{
  ConnectTelnet();

  var ip = req.connection.remoteAddress;


console.log(ip);
})

But the result I get is this: ":: 1"

Does anyone know why and how to fix it?

Thanks

    
asked by java005 24.09.2018 в 22:23
source

1 answer

2

In localhost you are getting ':: 1' because you are using IPv6, you could get ':: 1' (ipv6) or '127.0.0.1' (ipv4).

Try to access the url from another device.

In your code, check if you have the configuration for 'trust proxy'. By default this is false but if you have something like this:

app.set('trust proxy', true);

It means that it is activated, so to obtain the client's ip you should do:

var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

You can check the express documentation from where I got the information here , the information is just where it says 'Options for trust proxy setting'

    
answered by 25.09.2018 в 17:46