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
})
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In your
requestobject there is a property calledsocket, which is anet.Socketobject. Thenet.Socketobject has a propertyremoteAddress, therefore you should be able to get the IP with this call:(if your node version is below 13, use the deprecated now
request.connection.remoteAddress)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']EDIT 2
When using
expresswith Node.js:If you set
app.set('trust proxy', true),req.ipwill return the real IP address even if behind proxy. Check the documentation for further information