简体   繁体   中英

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.

There are numerous of tips & tricks all around stackoverflow but they are outdated and not working anymore.

It is in the 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.

Edit2 : Issue could be related to Client and Server version unaligned.

Currently theres an open issue : Remote address (IP) is always undefined #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.

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.conn.transport.socket._socket.remoteAddress

works with transports: ['websocket']

Successfully getting IP values using transports: ['websocket'] on the socket connection on all three keys below, version 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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