Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the correct IP address of a client into a Node socket.io app hosted on Heroku?

I recently hosted my first Node app using Express and socket.io on Heroku and need to find the client's IP address. So far I've tried socket.manager.handshaken[socket.id].address, socket.handshake.address and socket.connection.address , neither of which give the correct address.

App: http://nes-chat.herokuapp.com/ (also contains a link to GitHub repo)

To view IPs of connected users: http://nes-chat.herokuapp.com/users

Anyone know what the problem is?

like image 399
Douglas Avatar asked Jan 17 '13 15:01

Douglas


People also ask

How do I get IP client Nodejs?

The easiest way to find your IP address in Node. js is to pull the client IP address from the incoming HTTP request object. If you are running Express in your Node app, this is very easy to do. Access the socket field of the Express request object, and then look up the remoteAddress property of that field.


3 Answers

You can do it in one line.

function getClientIp(req) {
    // The X-Forwarded-For request header helps you identify the IP address of a client when you use HTTP/HTTPS load balancer.
    // http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-for
    // If the value were "client, proxy1, proxy2" you would receive the array ["client", "proxy1", "proxy2"]
    // http://expressjs.com/4x/api.html#req.ips
    var ip = req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',')[0] : req.connection.remoteAddress;
    console.log('IP: ', ip);
}

I like to add this to middleware and attach the IP to the request as my own custom object.

like image 24
Bernie Perez Avatar answered Nov 15 '22 08:11

Bernie Perez


The client IP address is passed in the X-Forwarded-For HTTP header. I haven't tested, but it looks like socket.io already takes this into account when determining the client IP.

You should also be able to just grab it yourself, here's a guide:

function getClientIp(req) {
  var ipAddress;
  // Amazon EC2 / Heroku workaround to get real client IP
  var forwardedIpsStr = req.header('x-forwarded-for'); 
  if (forwardedIpsStr) {
    // 'x-forwarded-for' header may return multiple IP addresses in
    // the format: "client IP, proxy 1 IP, proxy 2 IP" so take the
    // the first one
    var forwardedIps = forwardedIpsStr.split(',');
    ipAddress = forwardedIps[0];
  }
  if (!ipAddress) {
    // Ensure getting client IP address still works in
    // development environment
    ipAddress = req.connection.remoteAddress;
  }
  return ipAddress;
};
like image 189
friism Avatar answered Nov 15 '22 08:11

friism


The below worked for me.

Var client = require('socket.io').listen(8080).sockets;

client.on('connection',function(socket){ 
var clientIpAddress= socket.request.socket.remoteAddress;
});
like image 45
VoidA313 Avatar answered Nov 15 '22 08:11

VoidA313