Abilio Marques
Abilio Marques

Reputation: 161

Get remote IP adress not working on node

I'm trying to get the remote IP address from an incoming connection using express. Already tried the common solutions found in the web:

  1. req.headers['x-forwarded-for'] / result: always undefined
  2. req.socket.remoteAddress / result: always getting the Gateway IP (IE: 192.168.1.1) instead of the external address.

Any clues?

Upvotes: 2

Views: 4865

Answers (2)

eventi
eventi

Reputation: 87

Are you testing this by running the app in a VM on your own machine? If so, you're getting the right answer. The X-Forwarded-For is empty, since there's no proxy, and you're seeing the virtual interface on the host machine which the VM uses to route out from. That's the IP from which the request comes.

Upvotes: 0

eventi
eventi

Reputation: 87

Here's some code i used at http://th.issh.it/ip

Maybe it's case sensitive?

exports.iptoy = function(req,res) {
    var clientip = req.socket.remoteAddress;
    var xffip  = req.header('X-Forwarded-For');
    var ip = xffip ? xffip : clientip;
    if(req.params.format == 'json')
        res.send({client:clientip,xforwardedfor:xffip});
    else
        res.send(ip+"\n");
}

Upvotes: -3

Related Questions