Darker
Darker

Reputation: 83

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.

Upvotes: 4

Views: 7532

Answers (4)

Reece Daniels
Reece Daniels

Reputation: 1207

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

Upvotes: 0

Chris'
Chris'

Reputation: 14473

In socket.io 2.0: you can use:

socket.conn.transport.socket._socket.remoteAddress

works with transports: ['websocket']

Upvotes: 2

Eric
Eric

Reputation: 10626

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.

Upvotes: 4

EMX
EMX

Reputation: 6211

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

Upvotes: 3

Related Questions