McMatt
McMatt

Reputation: 129

Get IP of connection in socket.io 1.4.5

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.

Upvotes: 0

Views: 1758

Answers (1)

jfriend00
jfriend00

Reputation: 707148

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.

Upvotes: 2

Related Questions