如何使用socket.io获取客户端IP地址?

时间:2017-07-15 21:38:11

标签: node.js sockets nginx socket.io

我搜索了整个SO但我找不到答案。我想用socket io获取客户端IP地址。 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
   });
});

所以这段代码不起作用:

var ip = socket.request.socket.remoteAddress

这个不起作用:

var ip = socket.handshake.headers["x-forwarded-for"];
//var ip = socket.handshake.headers["X-Forwarded-For"];

使用此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地址

2 个答案:

答案 0 :(得分:0)

您可以尝试socket.handshake.addresssocket.handshake.address.substr(7)

答案 1 :(得分:0)

我更改了nginx配置并解决了问题:

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;
    }
}

并在sockets.js

module.exports = function(io, db) {
   io.on('connection', function(socket) {
        var ip = socket.handshake.headers["x-real-ip"];
   });
});