How to get ip in io socket

var app = require("express")();
var server = require("http").Server(app);
var io = require("socket.io")(server);
var requestIp = require('request-ip');
server.listen(3000);

var ipMiddleware = function(req, res) {
    return requestIp.getClientIp(req);
};

var ip = null;
app.get("/", function (req, res) {
   ip = ipMiddleware(req, res);
   res.sendFile(__dirname + "/index.html");
});

io.on("connection", function (socket) {
   // send the ip to user
});

My problem is that I would like to get the ip address of the client with the expression and fix the ip address for the client, ips are different, then this should be, how can I emit the ip that I get with the expression? thank

+4
source share
1 answer

you can use something like this. I use the method socket.ioto get the client IP address here.

io.on("connection", function (socket) {
    var clientIp = socket.request.connection.remoteAddress;
    socket.emit('eventName',{ip : clientIp}); //emit it back to client
});

check this fooobar.com/questions/54567 / ... to find out how to get client ip for different versions socket.io.

+9
source

All Articles