0

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.
McMatt
  • 129
  • 1
  • 14

1 Answers1

2

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Then how do I get the port? also the address prints out as ::ffff:then the ip or sometimes it just prints out as ::1 I'm not sure what's happening – McMatt Oct 08 '16 at 23:31
  • @McMatt - I don't know where you would find the port in socket.io. The incoming port is obviously whatever your server is listening on. What you're seeing for the IP address is probably an IPv6 form for localhost. Try when connecting from an external IP, not localhost. – jfriend00 Oct 08 '16 at 23:35
  • @McMatt - Here's some info about the IPv4 through IPv6 address format: [When is the hybrid IP notation ::ffff:192.168.1.4 appropriate?](http://stackoverflow.com/questions/5861107/when-is-the-hybrid-ip-notation-ffff192-168-1-4-appropriate). – jfriend00 Oct 08 '16 at 23:36
  • @McMatt - I added info about getting the port. – jfriend00 Oct 09 '16 at 07:30