How can I get the client IP from a request object with Restify?
Asked Answered
T

2

10

I'm having a difficult time finding how to access the IP address of the REST client from a route.

server.get('api/foo', function(req, res, next) {
    // How can I access the IP address of the requester from here?
}
Toxoplasmosis answered 26/1, 2015 at 20:38 Comment(1)
Try inspecting the req object.Rentsch
T
21

This worked:

req.connection.remoteAddress

Toxoplasmosis answered 26/1, 2015 at 21:9 Comment(0)
B
19

The other answers won't work behind a proxy, you'll get the proxy server address in those cases.

req.headers['x-forwarded-for'] || req.connection.remoteAddress;

Will work behind a proxy if the proxy sets the original IP in x-forwarded-for header which many do by default and you can add to something like nginx very easily.

Belittle answered 2/1, 2016 at 21:54 Comment(1)
x-forwarded-for can contain a chain of forwarding hosts. You should split it on coma separator and get the first (leftmost) IP. Or the first (leftmost) public IP if you need it for geolocation for example.Exemplum

© 2022 - 2024 — McMap. All rights reserved.