Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is socket.remoteAddress undefined on 'end' event?

I have a simple TCP server as follows:

var net = require('net');
var PORT = 6346;

var server = net.createServer(function(socket) {

    socket.on('connect', function() {
        console.log('Client connected: ' + socket.remoteAddress);
        socket.write('Welcome to the server!\r\n');
    });

    socket.on('end', function() {
        console.log('Client disconnected: ' + socket.remoteAddress);
    });

    socket.on('error', function() {
        console.log('Client error: ' + socket.remoteAddress);
    });

    socket.on('timeout', function() {
        console.log('Client timed out:' + socket.remoteAddress);
    });


}).listen(PORT);

When I connect to the server I see the expected Client connected: 127.0.0.1 but when I disconnect I see Client disconnected: undefined. Why is socket.remoteAddress undefined and how can I log the IP of the client upon disconnect?

like image 598
styfle Avatar asked Sep 16 '12 05:09

styfle


2 Answers

The problem is that after the socket is disconnected, certain properties (such as remoteAddress) are no longer available!

You can get around this by wrapping socket with your own object, or by keeping track of that remote address somewhere else upon connect. (Woot for closures.)

like image 127
Brad Avatar answered Nov 16 '22 05:11

Brad


The remoteAddress property will be around even after disconnect once https://github.com/joyent/node/commit/8c38b07252d86f4eef91344f8df4f0c3e38bca35 is in a stable version of Node.js. io.js will have it in the next release: https://github.com/iojs/io.js/issues/1157

like image 21
James Hartig Avatar answered Nov 16 '22 04:11

James Hartig