Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remote IP address with node-js behind amazon ELB

Tags:

node.js

ip

amazon

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?

like image 351
Johann Philipp Strathausen Avatar asked Aug 21 '11 16:08

Johann Philipp Strathausen


People also ask

Does ELB have IP address?

The short answer: Yes, ELB's IP addresses (both the ones that are publicly distributed to clients of your service, and the internal IPs from which ELB sends traffic to your instances) dynamically change.

How many IP address do we get with ELB?

The load balancer has one IP address per enabled Availability Zone. These are the addresses of the load balancer nodes.


2 Answers

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 );
like image 198
Mario Michelli Avatar answered Sep 18 '22 16:09

Mario Michelli


Here's a solution in case you are using express:
According to the documentation, you can enable trust proxy for your express instance and then req.ip will be populated with the correct ip address.

By enabling the "trust proxy" setting via app.enable('trust proxy'), Express will have knowledge that it's sitting behind a proxy and that the X-Forwarded-* header fields may be trusted, which otherwise may be easily spoofed.

Enabling this setting has several subtle effects. The first of which is that X-Forwarded-Proto may be set by the reverse proxy to tell the app that it is https or simply http. This value is reflected by req.protocol.

The second change this makes is the req.ip and req.ips values will be populated with X-Forwarded-For's list of addresses.

Here's an example:

var app = express();
app.enable('trust proxy');
// ...

app.use(function(req, res, next) {
  console.log('client ip address:', req.ip);
  return next();
});
like image 25
Michael Avatar answered Sep 18 '22 16:09

Michael