【发布时间】:2017-08-28 17:51:39
【问题描述】:
我目前在 node.js 服务器中使用 socket.io v2.0.3 并且找不到获取客户端 IP 地址的方法。
stackoverflow 周围有许多提示和技巧,但它们已经过时并且不再起作用了。
【问题讨论】:
标签: javascript node.js socket.io
我目前在 node.js 服务器中使用 socket.io v2.0.3 并且找不到获取客户端 IP 地址的方法。
stackoverflow 周围有许多提示和技巧,但它们已经过时并且不再起作用了。
【问题讨论】:
标签: javascript node.js socket.io
它在 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:问题可能与未对齐的客户端和服务器版本有关。
【讨论】:
undefined。
目前有一个未解决的问题: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
【讨论】:
socket.handshake.address 和 socket.request.connection._peername.address 似乎都可以正常工作,但是当您在客户端中使用 transports: ['websocket'] 时,socket.hanshake.address 和 socket.request.connection._peername 是 undefined。希望尽快修复
client.request.connection._peername 在我的场景中不存在。到目前为止,只有将服务器降级到 1.7.4 才有效。
在 socket.io 2.0 中:您可以使用:
socket.conn.transport.socket._socket.remoteAddress
适用于transports: ['websocket']
【讨论】:
在下面所有三个键的套接字连接上使用transports: ['websocket'] 成功获取IP 值,版本2.3.0。
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
【讨论】: