如何在socket.io 2.0.3中获取客户端ip地址



我目前在node.js服务器中使用socket.io v2.0.3,找不到获取客户端IP地址的方法。

这里有许多提示&stackoverflow的所有技巧,但它们已经过时,不再有效了。

它在套接字中。握手

{
headers: /* the headers sent as part of the handshake */,
time: /* the date of creation (as string) */,
address: /* the ip of the client */,
xdomain: /* whether the connection is cross-domain */,
secure: /* whether the connection is secure */,
issued: /* the date of creation (as unix timestamp) */,
url: /* the request URL string */,
query: /* the query object */
}

请参阅此链接

编辑:将其更改为socket.request.connection.remoteAddress,请参阅此链接。

第2版:问题可能与客户端和服务器版本未对齐有关。

目前有一个悬而未决的问题:远程地址(IP(总是未定义#2982

我相信它很快就会得到修复,在那之前没有理由降级,如果你真的需要获得客户端IP,有一个可能的解决方案。

概念验证:

const socketServer = require('socket.io')(3000)
socketServer.on('connection',function(client){
console.log( client.request.connection._peername.address );
})
const socketCli = require('socket.io-client')('http://localhost:3000')

输出:

::ffff:127.0.0.1

在socket.io 2.0中:您可以使用:

socket.conn.transport.socket._socket.remoteAddress

transports: ['websocket']配合使用

在以下所有三个密钥(版本2.3.0(的套接字连接上使用transports: ['websocket']成功获取IP值。

socket.request.connection.remoteAddress ::ffff:127.0.0.1
socket.conn.remoteAddress ::ffff:127.0.0.1
socket.conn.transport.socket._socket.remoteAddress ::ffff:127.0.0.1

最新更新