Get IP of connection in socket.io 1.4.5

独自空忆成欢 提交于 2019-12-25 09:13:51

问题


I would like to know how to get the IP of a user when they connect to the server n socket.io. I have tried using this code which is supposed to log the connection address and port like this:

var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
  var address = socket.handshake.address;
  console.log('New connection from ' + address.address + ':' + address.port);
  socket.on('request', function(data) {
    console.log('Request Sent')
    length = data.length
    if (data.request == 'sessionID') {
      socket.emit('sendSessionID', {
        id: generateSessionID(length)
      });
      console.log('Sent session ID')
    }
    if (data.request == 'players') {

    }
  });
});
When I run this code though address.address is undefined and same with address.port. So how am I supposed to get the IP and port when I'm using 1.4.5? I can not find anything that is newly updated.

回答1:


The IP address is in socket.handshake.address, not socket.handshake.address.address.


Though none of this appears to be documented in socket.io, you can get the remote IP address and the remote port with these:

socket.request.connection.remoteAddress
socket.request.connection.remotePort

When I connect to a socket.io server from another computer on my LAN, I see these output from those above two settings:

::ffff:192.168.1.56
51210

This is correctly giving you the IP address and the port of the remote computer that is connecting to your server. The IP address ::ffff:192.168.1.56 is an IPv4 mapped address. You will have to handle that form of address on some systems.



来源:https://stackoverflow.com/questions/39937902/get-ip-of-connection-in-socket-io-1-4-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!