Reputation: 2361
I've searched the whole SO but I couldn't find my answer. I want to get client IP address with socket io. v2.0.3
app.js
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
/// other imports ...
//with or without this line nothing changes
io.set('transports', ['websocket']);
app.use(function(req, res, next) {
req.db = db;
next();
});
require('./sockets')(io, db);
sockets.js
module.exports = function(io, db) {
io.on('connection', function(socket) {
var ip = socket.request.socket.remoteAddress ; // undefined
//var ip = socket.handshake.headers["x-forwarded-for"]; undefined
//var ip = socket.handshake.headers["X-Forwarded-For"]; undefined
});
});
so this code does not work:
var ip = socket.request.socket.remoteAddress
this one does not work eather:
var ip = socket.handshake.headers["x-forwarded-for"];
//var ip = socket.handshake.headers["X-Forwarded-For"];
with this nginx config:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
is there anyway to get the client IP address with socket.io?
Upvotes: 0
Views: 1629
Reputation: 1313
You can try socket.handshake.address
or socket.handshake.address.substr(7)
Upvotes: 0
Reputation: 2361
I changed nginx config and the problem solved:
server {
listen 80;
server_name example.com;
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Real-IP;
real_ip_recursive on;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto https;
}
}
and in sockets.js
module.exports = function(io, db) {
io.on('connection', function(socket) {
var ip = socket.handshake.headers["x-real-ip"];
});
});
Upvotes: 1