How can I determine the IP address of a given request from within a controller? For example (in express):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
How can I determine the IP address of a given request from within a controller? For example (in express):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
You can stay DRY and just use node-ipware that supports both IPv4 and IPv6.
Install:
In your app.js or middleware:
It will make the best attempt to get the user's IP address or returns
127.0.0.1
to indicate that it could not determine the user's IP address. Take a look at the README file for advanced options.request.headers['x-forwarded-for'] || request.connection.remoteAddress
If the
x-forwarded-for
header is there then use that, otherwise use the.remoteAddress
property.The
x-forwarded-for
header is added to requests that pass through load balancers (or other types of proxy) set up for HTTP or HTTPS (it's also possible to add this header to requests when balancing at a TCP level using proxy protocol). This is because therequest.connection.remoteAddress
property will contain the private ip address of the load balancer rather than the public ip address of the client. By using an OR statement, in the order above, you check for the existence of anx-forwarded-for
header and use it if it exists otherwise use therequest.connection.remoteAddress
.Simple get remote ip in nodejs:
If you're using express version 3.x or greater, you can use the trust proxy setting (http://expressjs.com/api.html#trust.proxy.options.table) and it will walk the chain of addresses in the x-forwarded-for header and put the latest ip in the chain that you've not configured as a trusted proxy into the ip property on the req object.
In your
request
object there is a property calledconnection
, which is anet.Socket
object. The net.Socket object has a propertyremoteAddress
, therefore you should be able to get the IP with this call:See documentation for http and net
EDIT
As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is
request.headers['x-forwarded-for']