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

4

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

虽然stackoverflow上有很多提示和技巧,但它们已经过时并且不再起作用。

4个回答

4

它位于 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 */
}

看看这个链接:这里 编辑:据说已更改为 socket.request.connection.remoteAddress,请看这里
编辑2:问题可能与客户端和服务器版本不一致有关。

这是我看到的:{ "headers":{ "user-agent":"websocket-sharp/1.0", "upgrade":"websocket", "connection":"Upgrade", "host":"11.111.11.11:3000", "sec-websocket-key":"WOY2i4lbneGJp/8L+dPHSQ==", "sec-websocket-version":"13" }, "time":"Mon Aug 28 2017 14:02:43 GMT-0400 (EDT)", "xdomain":false, "secure":false, "issued":1503943363593, "url":"/socket.io/?EIO=4&transport=websocket", "query":{ "EIO":"4", "transport":"websocket" } } - Darker
感觉它们又改变了一些东西。socket.handshake.headers.host 不是你的客户端 IP 吗? - Eric
然后尝试使用socket.request.connection.remoteAddress。 - Eric
这也是 undefined - Darker
也许尝试使用socket.conn.remoteAddress。 - Eric
显示剩余8条评论

3

目前存在一个未解决的问题:远程地址(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.handshake.addresssocket.request.connection._peername.address似乎都能正常工作,但是当您在客户端使用transports: ['websocket']时,socket.hanshake.addresssocket.request.connection._peername都会变成undefined。希望这个问题能够尽快得到解决。 - mk12ok
1
似乎在我的情况下 client.request.connection._peername 不存在。到目前为止,只有将服务器降级到 1.7.4 才有效。 - Darker

2
在socket.io 2.0中,您可以使用以下代码来获取远程地址:socket.conn.transport.socket._socket.remoteAddress,该方法适用于transports: ['websocket']

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接