'Remote IP address with node-js behind amazon ELB

I have a node application on an instance-store amazon machine behind the elastic load balancer (elb). However, the remote IP adress seems to always be the same. I used this code to get the client's IP address in node (via connect/express):

req.socket.remoteAddress

I didn't get anything else from the node documentation. Any hint?



Solution 1:[1]

The answer worked for me, thanks. But you may just try:

var ip_address = null;
if(req.headers['x-forwarded-for']){
    ip_address = req.headers['x-forwarded-for'];
}
else {
    ip_address = req.connection.remoteAddress;
}
sys.puts( ip_address );

Solution 2:[2]

Your receiving the IP of the ELB instance and you'll need to get the x-forwarded-for value from the headers. Since I'm not a node.js guru, I found this code at http://forum.webfaction.com/viewtopic.php?id=4500

Example:

var http = require( 'http' ),
sys = require( 'sys' );

http.createServer(
        function( req, res ) {
                        var ip_address = null;
                        try {
                                ip_address = req.headers['x-forwarded-for'];
                        }
                        catch ( error ) {
                                ip_address = req.connection.remoteAddress;
                        }
                        sys.puts( ip_address );
        }
);

Solution 3:[3]

The selected correct answer here is dangerous, because AWS ELBs switch the order as expected: https://github.com/koajs/koa/issues/1094#issuecomment-345861282

Express, koa, etc. typically take the left-most item, while ELB makes it the right-most item

(express docs):

If true, the client’s IP address is understood as the left-most entry in the X-Forwarded-For header.

Solution 4:[4]

In case if express.js is in use:

app.set('trust proxy', 2)

Instead of

app.enable('trust proxy')

Because the app.enable('trust proxy') uses the leftmost ip from the x-forwarded-for header and so can be easily spoofed by just providing x-forwarded-for header manually.

While the app.set('trust proxy', 2) has the number of hops specified that being counted from right to left of the x-forwarded-for header. I.e. if there is an AWS load balancer than 2 will be the right number to count because each new hop ip is added to the end of the x-forwarded-for header.

If you're using something else then do the similar way. Just get the req.headers['x-forwarded-for'], split by coma and then count hops from right to left until load balancer ip is not excluded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mario Michelli
Solution 2 joet3ch
Solution 3 danthegoodman
Solution 4