简体   繁体   中英

How can I get the client IP address with socket.io?

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?

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"];
   });
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM