1

I want to retrieve the client's IP address before I redirect the client to an external URL.

Here is my code:

Router.route('/:_id', {name: 'urlRedirect', where: 'server'}).get(function () {
    var url = Urls.findOne(this.params._id);
    if (url) {
        var request = this.request;
        var response = this.response;
        var headers = request.headers;
        console.log(headers['user-agent']);
        this.response.writeHead(302, {
            'Location': url.url
        });
        this.response.end();
    } else {
        this.redirect('/');
    }
});

My question is: Can I get the IP address from the request object?

SylvainB
  • 4,765
  • 2
  • 26
  • 39
user3475602
  • 1,217
  • 2
  • 21
  • 43

1 Answers1

2

According to the Iron-Router guide, the request you get from this.request will be a typical NodeJS request object:

Router.route('/download/:file', function () {
  // NodeJS request object
  var request = this.request;

  // NodeJS  response object
  var response = this.response;

  this.response.end('file download content\n');
}, {where: 'server'});

So you should be able to loop the IP address up in this.request.connection.remoteAddress.

As stated in this answer, you may also have to look in this.request.headers['x-forwarded-for'] in some cases.

Community
  • 1
  • 1
SylvainB
  • 4,765
  • 2
  • 26
  • 39
  • I tried it, the result is `127.0.0.1`. So I guess localhost is correct if my application runs on `127.0.0.1:3000`? – user3475602 Aug 19 '15 at 13:36
  • Pretty much, yes! You should try connecting to your local network using another device (a smartphone works) and go to `http://:3000`. Then you should get the other device's local IP in your results. – SylvainB Aug 19 '15 at 13:37
  • I tried it from my iPhone but I got also `127.0.0.1`, even though I used the computer's IP address. Any idea? – user3475602 Aug 19 '15 at 13:42
  • `this.request.headers['x-forwarded-for']` returns on my machine `127.0.0.1` and on my iPhone the internal IP address. Is it possible to get the external IP address? – user3475602 Aug 19 '15 at 14:00
  • Yes you would get the external IP address, just not from a device on the local network where your server is connected. Which is good! Since you don't want all the devices in your local network to show the same external IP. That way, even when requests come from the local network, you are able to trace them. – SylvainB Aug 19 '15 at 14:04
  • Try using your phone from an outside network (another Wifi or 3G for example) and you will get its external IP this time. – SylvainB Aug 19 '15 at 14:05
  • Thank you for your explanation! – user3475602 Aug 19 '15 at 14:15
  • Thank you for the prompt feedback as well. I edited my answer to mention `headers['x-forwarded-for']` – SylvainB Aug 19 '15 at 14:19