Sulli
Sulli

Reputation: 839

Node.js - Socket.io : socket.request undefined

I have read here that I can get client's IP in node.js with

socket.request.connection.remoteAddress

for example:

var socket = io.listen(server);
socket.on('connection', function(client){
    var client_ip_address = socket.request.connection.remoteAddress;
}

But when I use this solution I get the error message "Cannot read property 'connection' of undefined" which means that socket.request is undefined.

Why would that be the case?

I have also tried another option found on the same page:

var sHeaders = socket.handshake.headers;
console.info('[%s:%s] CONNECT', sHeaders['x-forwarded-for'], sHeaders['x-forwarded-port']);

but this just outputs

[undefined:undefined] CONNECT

Upvotes: 3

Views: 6058

Answers (3)

user1871391
user1871391

Reputation: 29

in socketio.js, simply update:

 console.info('[%s] DISCONNECTED', socket.address);

to:

 console.info('[%s] DISCONNECTED', socket.handshake.address);

Same for the CONNECTED logs.

Upvotes: 0

rahpuser
rahpuser

Reputation: 1249

var server = require('http').Server(app);
var io = socketIO(server);

io.on('connection', function(socket) {
    console.log('client IP: ',socket.handshake.address);
// this should work too
    console.log('client IP: ',socket.client.conn.remoteAddress);
// or
    console.log('client IP: ',socket.conn.remoteAddress);
});

server.listen(3000);

I just read that you are using heroku.. Well makes sense that you get a different ip Address, usually web traffic in heroku is over a proxy.. because of that you wouldnt be able to get the remoteAddress..

Upvotes: 0

tkit
tkit

Reputation: 8632

I just tried something like this on my computer and it returned 127.0.0.1 which is correct:

var express = require('express');
var io = require('socket.io');
var path = require('path');

var app = express();
var server = http.createServer(app);
var ioServer = io.listen(server);

ioServer.sockets.on('connection', function (socket) {
    console.log(socket.request.connection.remoteAddress);
    // This gave 127.0.0.1
});

The socket from your code is not the clients socket connection but the "server" itself so it's normal that it does not have a request property. Use the code I wrote or try changing:

socket.on(

to:

socket.sockets.on(

and:

socket.request.connection.remoteAddress

to (for Express v4.x, Socket.IO v1.x):

client.request.connection.remoteAddress

or (for Express v3.x, Socket.IO v0.x) (this apparently returns the server IP):

socket.handshake.address

and it should give you what you need.

EDIT: If I remember correctly socket.io versions < 1.x don't use client.request but rather client.handshake so try that one.

To upgrade express and socket.io, check these two links:

Upvotes: 2

Related Questions