在socket.io 1.4.5中获取连接的IP [英] Get IP of connection in socket.io 1.4.5

查看:921
本文介绍了在socket.io 1.4.5中获取连接的IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在用户连接到服务器n socket.io时获取用户的IP。我试过使用这个代码来记录连接地址和端口,如下所示:

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') {

    }
  });
});


当我运行此代码虽然address.address未定义且与address.port相同。那么当我使用1.4.5时,我应该如何获得IP和端口?我找不到任何新更新的内容。

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.

推荐答案

IP地址在 socket.handshake中。地址,而不是 socket.handshake.address.address

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

虽然socket.io中似乎没有记录这些内容,但您可以使用以下内容获取远程IP地址和远程端口:

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

当我从LAN上的另一台计算机连接到socket.io服务器时,我看到以上两种设置的输出:

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

这是正确的给予您连接到服务器的远程计算机的IP地址和端口。 IP地址 :: ffff:192.168.1.56 是IPv4映射地址。你必须在某些系统上处理这种形式的地址。

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.

这篇关于在socket.io 1.4.5中获取连接的IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆