Saw lot ot tutorials, articles and stackoverflow questions about getting the client IP address from NodeJS.
Almost all of them use this request.header('x-forwarded-for')
My NodeJS v0.8.7
doesnt have that request.header function.
typeof request.header
returns undefined
However I have request.headers that is an object containing some info:
{ host: '127.0.0.1:8000',
connection: 'keep-alive',
accept: '*/*',
'user-agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'en-US,en;q=0.8',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' }
The host value seemed to be worth of checking out. Running node on localhost obviously returned 127.0.0.1:8000
, but then I tried accessing my node.js site from my netbook on the same network, pointing to 192.168.0.13 (my desktop IP in which node is running) and I got 192.168.0.13:8000
. So its not giving me the client IP but which IP im using to point to the app.
I tried then request.connection.remoteAddress
as it got named over the tutorials I found. Running from localhost gave 127.0.0.1
, and from my netbook 192.168.0.12
. So it worked! 192.168.0.12 is my netbook IP.
But over the tutorials and questions I found they say that the correct way would be the first one, depending if the proxy is yours or not.
So what would be the right way to do it? and why request.header doesnt exist to me?
If you're using express 3, you can do this:
req.ip
// => "127.0.0.1"
http://expressjs.com/api.html#req.ip
If you want other headers, you can use this:
req.get(field)
req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined
http://expressjs.com/api.html#req.get
If you're using plain node, use this:
request.headers