Get the client's IP address in socket.io
Okay, as of 0.7.7 this is available, but not in the manner that lubar describes. I ended up needing to parse through some commit logs on git hub to figure this one out, but the following code does actually work for me now:
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
var address = socket.handshake.address;
console.log('New connection from ' + address.address + ':' + address.port);
});
for 1.0.4:
io.sockets.on('connection', function (socket) {
var socketId = socket.id;
var clientIp = socket.request.connection.remoteAddress;
console.log(clientIp);
});
If you use an other server as reverse proxy all of the mentioned fields will contain localhost. The easiest workaround is to add headers for ip/port in the proxy server.
Example for nginx:
add this after your proxy_pass
:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
This will make the headers available in the socket.io node server:
var ip = socket.handshake.headers["x-real-ip"];
var port = socket.handshake.headers["x-real-port"];
Note that the header is internally converted to lower case.
If you are connecting the node server directly to the client,
var ip = socket.conn.remoteAddress;
works with socket.io version 1.4.6 for me.