我搜索了整個SO,但我找不到我的答案。我想用socket io獲取客戶端IP地址。 v2.0.3
app.js如何使用socket.io獲取客戶端IP地址?
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
});
});
所以這段代碼不起作用:
var ip = socket.request.socket.remoteAddress
這一個不eather工作:
var ip = socket.handshake.headers["x-forwarded-for"];
//var ip = socket.handshake.headers["X-Forwarded-For"];
風趣h這個nginx配置:
server {
listen 80;
server_name example.com;
location/{
proxy_pass http://localhost:3000;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
是否有無論如何獲得與socket.io客戶端IP地址?
你明白了什麼,當您嘗試使用的第一個? – Wright
@Wright:'undefined' – smoqadam
如果你可以發佈一些代碼來給出你使用它的地方的上下文,這將有所幫助。這個對我有用。 – Wright