1

For my current project, I need to get the remote IP address in a Node.js http.createServer((req,res)=>{}); function. I've tried looking through the API documentation for Node.js itself, with no luck, then turning to Google, with most answers appearing to use Express.js. The answers seemed to point at req.connection.remoteAddress (which works, but breaks if used with a proxy) or req.headers['x-forwarded-for'], however this returned undefined when I tried to use it. Any help is greatly appreciated.

2 Answers 2

7

You almost had it, try:

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

This will set clientip to the correct value if a proxy is used. If no proxy is used, clientip gets set to the ip address of the client initiating the connection.

2
  • 1
    When running on localhost, I get ::1, is that an intended result?
    – LostEth0
    Dec 15, 2019 at 19:30
  • 3
    ::1 is the ipv6 equivalent to 127.0.0.1. If your server has ipv6 enabled this is as expected.
    – mottek
    Dec 15, 2019 at 21:53
0

'connection' is deprecated. since v13.0.0 - Use socket instead.

const clientip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.