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

I have a simple TCP server:

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 register the client IP address when disconnected?

+6
source share
3 answers

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

You can get around this by wrapping the socket with your own object, or by tracking this remote address somewhere else when connected. (Woot for closures.)

+9
source

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

+2
source

When I tried to debug 504 errors from specific servers, I found that changing this code

 request(url, function (error, response, body) { if (error) { callback(error); } else { if (response.statusCode == 200) { callback(null, body); } else { // response.connection.remoteAddress is undefined here callback(new Error("Non status 200: " + response.statusCode + " received from " + response.connection.remoteAddress + " when requesting " + url)); } } }); 

to this code

 request(url, function (error, response, body) { if (error) { callback(error); } else { if (response.statusCode == 200) { callback(null, body); } else { // response.connection.remoteAddress is now magically set somehow callback(new Error("Non status 200: " + response.statusCode + " received from " + response.connection.remoteAddress + " when requesting " + url)); } } }).on('response', function(response) { // This next line is very important. It seems to make the remoteAddress variable stay in the socket so we can read it. let remoteAddress = response.connection.remoteAddress; }); 

seemed to work. I have no idea why accessing the remoteAddress variable in the response handler forces it to remain in place for reading.

0
source

Source: https://habr.com/ru/post/1434429/


All Articles