简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM