【问题标题】:How to get client ip address in socket.io 2.0.3?如何在 socket.io 2.0.3 中获取客户端 IP 地址?
【发布时间】:2017-08-28 17:51:39
【问题描述】:

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

stackoverflow 周围有许多提示和技巧,但它们已经过时并且不再起作用了。

【问题讨论】:

    标签: javascript node.js socket.io


    【解决方案1】:

    它在 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:问题可能与未对齐的客户端和服务器版本有关。

    【讨论】:

    • 这是我看到的:{ "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":"8 月 28 日星期一2017 14:02:43 GMT-0400 (EDT)", "xdomain":false, "secure":false, "issued":1503943363593, "url":"/socket.io/?EIO=4&transport=websocket", "查询":{ "EIO":"4", "传输":"websocket" } }
    • 感觉他们又改变了一些东西。 socket.handshake.headers.host 不是你的客户端ip吗?
    • 不,那是服务器的IP。
    • 那就试试socket.request.connection.remoteAddress
    • 那也是undefined
    【解决方案2】:

    目前有一个未解决的问题: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.addresssocket.request.connection._peername.address 似乎都可以正常工作,但是当您在客户端中使用 transports: ['websocket'] 时,socket.hanshake.addresssocket.request.connection._peernameundefined。希望尽快修复
    • 似乎client.request.connection._peername 在我的场景中不存在。到目前为止,只有将服务器降级到 1.7.4 才有效。
    【解决方案3】:

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

    socket.conn.transport.socket._socket.remoteAddress

    适用于transports: ['websocket']

    【讨论】:

      【解决方案4】:

      在下面所有三个键的套接字连接上使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-21
        • 2017-12-20
        • 1970-01-01
        • 2012-03-14
        • 2012-02-16
        • 2019-01-14
        • 2021-10-22
        相关资源
        最近更新 更多