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

时间:2017-08-28 17:51:39

标签: javascript node.js socket.io

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

有许多提示&在stackoverflow周围捣乱,但它们已经过时,不再工作了。

4 个答案:

答案 0 :(得分:3)

它位于 socket.handshake

{
  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 */
}

请参阅this链接

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

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

答案 1 :(得分:3)

目前还有一个未解决的问题:Remote address (IP) is always undefined #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

答案 2 :(得分:2)

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

socket.conn.transport.socket._socket.remoteAddress

适用于transports: ['websocket']

答案 3 :(得分:0)

在下面所有三个键(版本transports: ['websocket'])上的套接字连接上使用2.3.0成功获取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
相关问题