简体   繁体   English

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

[英]How to get client ip address in socket.io 2.0.3?

I am currently using socket.io v2.0.3 in node.js server and can't find a way to get client's IP address.我目前在 node.js 服务器中使用 socket.io v2.0.3,但找不到获取客户端 IP 地址的方法。

There are numerous of tips & tricks all around stackoverflow but they are outdated and not working anymore. stackoverflow 周围有许多提示和技巧,但它们已经过时且不再有效。

It is in the socket.handshake它在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 */
}

See this link这个链接

Edit: turns it it might have changed to socket.request.connection.remoteAddress , see this link.编辑:它可能已更改为socket.request.connection.remoteAddress ,请参阅链接。

Edit2 : Issue could be related to Client and Server version unaligned. Edit2 :问题可能与客户端和服务器版本未对齐有关。

Currently theres an open issue : Remote address (IP) is always undefined #2982目前有一个未解决的问题:远程地址 (IP) 始终未定义 #2982

I'm sure it will get fixed soon, until then there is no reason to downgrade if you really need to obtain the clients IP there is a possible solution.我相信它会很快得到修复,在此之前,如果您确实需要获取客户端 IP,则没有理由降级,有可能的解决方案。

proof of concept:概念证明:

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

output:输出:

::ffff:127.0.0.1

In socket.io 2.0: you can use:在 socket.io 2.0 中:您可以使用:

socket.conn.transport.socket._socket.remoteAddress

works with transports: ['websocket']适用于transports: ['websocket']

Successfully getting IP values using transports: ['websocket'] on the socket connection on all three keys below, version 2.3.0 .使用transports: ['websocket']成功获取 IP 值transports: ['websocket']在以下所有三个键的套接字连接上,版本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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM