I've written the following function:
let responses = {}
let socks = {}
module.ping = function (port, address) {
//console.log(`Ping function was called - ${address} ${port}`)
if (socks[`${address}:${port}`]) {
//console.log("Using existing socket")
responses[`${address}:${port}`] = false
sock = socks[`${address}:${port}`]
sock.write('PING\n')
console.log(`Sent PING to ${address} ${port}`)
}
else {
sock = new net.Socket();
responses[`${address}:${port}`] = false
sock.connect(port, address, async function() {
sock.write('PING\n')
console.log(`Sent PING to ${address} ${port}`)
});
// Response listeners
sock.on('data', function(data) {
clean_data = data.toString().replace(/\n/g, '').replace(/\r/g, '')
console.log(`[${sock.remoteAddress}:${sock.remotePort}] Received ${clean_data}`)
if (clean_data == 'PONG') {
//console.log(`[${sock.remoteAddress}:${sock.remotePort}] Received PONG`)
//sock.end()
//delete socks[`${address}:${port}`]
responses[`${sock.remoteAddress}:${sock.remotePort}`] = true
}
}
});
sock.on('error', function(error) {
if (sock.remoteAddress) {
responses[`${sock.remoteAddress}:${sock.remotePort}`] = false
}
sock.destroy()
delete socks[`${address}:${port}`]
});
// Add to list of sockets
if (sock) {
socks[`${address}:${port}`] = sock
}
}
}
On the other end, I have a listening TCP server that simple responds with "PONG\n". When I try a single host I get the expected output:
module.ping(1337, 10.0.0.100)
await delay(5000) // Custom function
module.ping(1337, 10.0.0.100)
Sent PING to 10.0.0.100 1337
[10.0.0.100:1337] Received PONG
Sent PING to 10.0.0.100 1337
[10.0.0.100:1337] Received PONG
However when I attempt to hit multiple hosts:
module.ping(1337, 10.0.0.100)
module.ping(1337, 10.0.0.200)
await delay(5000) // Custom function
module.ping(1337, 10.0.0.100)
module.ping(1337, 10.0.0.200)
Sent PING to 10.0.0.100 1337
Sent PING to 10.0.0.200 1337
[10.0.0.200:1337] Received PONG
[10.0.0.200:1337] Received PONG
Sent PING to 10.0.0.100 1337
Sent PING to 10.0.0.200 1337
[10.0.0.200:1337] Received PONG
[10.0.0.200:1337] Received PONG
It seems to me that the event listener for "data" I've added has somehow bound to the incorrect address within my code, however I can't see where. If I add more hosts to the list, the last host with the PING sent is the one that all the PONGs are marked as part of.