I'm making a simple server in node.js using the TLS module. So far so good, clients are able to connect, send data, and disconnect from the server. However, I want to print the client's IP address when disconnecting from the server. As it stands, I'm able to print the client's IP address from outside the event callback functions, but I can't do so within the callbacks (check on('end)
).
var tls = require('tls');
var fs = require('fs');
var server = tls.createServer({
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
}, function(cleartextStream) {
cleartextStream.setEncoding('utf8');
/*
* Error receiving data.
*/
cleartextStream.on('error', function (exception) {
});
/*
* Signal that it is safe to write again.
*/
cleartextStream.on('drain', function () {
});
/*
* New data received.
*/
cleartextStream.on('data', function (data) {
console.log('New data: '+data);
});
/*
* Remote client disconnected.
*/
console.log(cleartextStream.remoteAddress); // This prints the IP address correctly.
cleartextStream.on('end', function () {
console.log(cleartextStream.remoteAddress); // This prints undefined.
});
/*
* Server is shutting down.
*/
cleartextStream.on('close', function () {
});
});
server.listen(8000, function() {
console.log('Server listening.');
});
Looks like the remoteAddress
property of cleartextStream
is removed prior to the 'end'
event firing. So capture the remote address so it's still available in your 'end'
event callback:
var remoteAddress = cleartextStream.remoteAddress;
cleartextStream.on('end', function () {
console.log(remoteAddress);
});