Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: print websocket client IP

node.js WebSocket example code snippet

I have a simple node.js application using express. Now everytime a client connects to the node server I see the string 'new client connected' but I would like to know which IP the new client had.

var WebSocketServer = require('ws').Server;
var connIds = [];

var server = require('http').createServer(app).listen(80);

// set up the websocket server
var wss = new WebSocketServer( { server: server } );
wss.clientConnections = {};

// websocket server eventlisteners and callbacks
wss.on('connection', function (connection) {
  console.log('wss.on.connection - new client connected');
  ...

See the code at: https://github.com/qknight/relais.js/blob/master/relais.js/server.js#L159

question

The object connection has properties but I don't understand how to query them or what they are. All I want is to print the client IP and maybe, if existent, other similar properties as well.

How do I do that?

like image 343
qknight Avatar asked Feb 22 '14 13:02

qknight


1 Answers

Remote IP is a property of the pre-upgrade connection:

var wss = new WebSocketServer({port: 9876});    

wss.on('connection', function(ws) {
  console.log(ws.upgradeReq.connection.remoteAddress);
});

i don't recall how i found it, but i know it took me a while; i wish the docs were as good as the code...

UPDATE: WS has moved some things around, so here's an updated example of how to get the original HTTP info in current code. Note the 2nd argument to the connection event handler:

wss.on('connection', function conn(ws, req) {
    var ip  =  req.connection.remoteAddress;
    console.info(ip);
});
like image 73
dandavis Avatar answered Oct 21 '22 19:10

dandavis