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?
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.
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.
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;
};
The below worked for me.
Var client = require('socket.io').listen(8080).sockets;
client.on('connection',function(socket){
var clientIpAddress= socket.request.socket.remoteAddress;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With