Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ip in socket io

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, I would like to get ip address of client with express and emit the ip address to client, ips are the different ones then it should be, how can I emit the ip I get with express ? thank you

like image 479
Mike Avatar asked Jan 08 '23 03:01

Mike


1 Answers

you can use something like this . I am using a socket.io method to 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 stackoverflow thread to know how to get client ip for different socket.io versions .

like image 178
Sojan Jose Avatar answered Jan 25 '23 19:01

Sojan Jose