簡體   English   中英

如何在 socket.io 2.0.3 中獲取客戶端 IP 地址?

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

我目前在 node.js 服務器中使用 socket.io v2.0.3,但找不到獲取客戶端 IP 地址的方法。

stackoverflow 周圍有許多提示和技巧,但它們已經過時且不再有效。

它在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 ,請參閱鏈接。

Edit2 :問題可能與客戶端和服務器版本未對齊有關。

目前有一個未解決的問題:遠程地址 (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.io 2.0 中:您可以使用:

socket.conn.transport.socket._socket.remoteAddress

適用於transports: ['websocket']

使用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