Reputation: 3010
I have a legit business need to test the way our server works using a fake IP address. We use request.ip
in a bunch of different places and I'd rather not have to replace every single instance of "request.ip" with the fake IP address, so I figured I would just redefine it at the application's entrypoint (the start of the callback chain). However, I ran into some unexpected behavior when request.ip
apparently changed itself back to "127.0.0.1"!
This is the (CoffeeScript) code I inserted into the "handle" method:
spanishIp ='37.35.128.128'
request.ip = spanishIp
console.log "ip: #{request.ip} / #{spanishIp}"
Resulting in the following log:
ip: 127.0.0.1 / 37.35.128.128
Evidently, request.ip
got redefined back to my actual IP address (127.0.0.1) in between setting it to "37.35.128.128" and the console.log statement.
When I moved my code one step further into the callback chain, it worked as expected.
Is it possible that Node/Express has some internal mechanism that repeatedly sets request.ip
to the user's actual IP address at runtime?
Upvotes: 1
Views: 2438
Reputation: 1058
The req.ip property in express is always pulled from the req.ips array via a function call, and it is built from the X-Forwarded-For header.
https://github.com/strongloop/express/blob/master/lib/request.js#L285-L287
So when you ask for req.ip, it is always going to return the value from req.ips array. Aka, you cannot "set" the req.ip property. You need to instead use the request body, like req.body.ip
if you need to do anything manual.
Upvotes: 2
Reputation: 7742
Trying to spoof the ip address by fiddling around with core functionality of node / expressjs does not sound like the right approach. I would recommend you instead to enable 'trust proxy'
in your app, and then spoof the IP address by using X-Forwarded-*
header. See this for more details.
EDIT:
If you really want to mock
the ip address of incoming requests, then might be worth looking at this. Again, I don't think node / expressjs
was designed to allow modification of req.ip
for any purpose at all.
Upvotes: 2