Check for internet connectivity using TCP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { createConnection } = require("net"); | |
function checkTCP(host = "1.1.1.1", port = 53) { | |
return new Promise((resolve, reject) => { | |
const client = createConnection({ host, port }, () => { | |
console.log(`TCP connection established on port ${port}`); | |
client.end(); | |
resolve(); | |
}); | |
client.setTimeout(3000); | |
client.on("timeout", err => { | |
console.error(`TCP connection on port ${port} timed out`); | |
client.destroy(); | |
reject(err); | |
}); | |
client.on("error", err => { | |
console.error(`Error trying to connect via TCP on port ${port}`); | |
reject(err); | |
}); | |
}); | |
} |
Example, how to check for an SSH connection at 192.168.1.1 on port 22:
let isOnline;
checkTCP("192.168.1.1", 22)
.then(() => (isOnline = true))
.catch(() => (isOnline = false))
.finally(() => console.log({ isOnline }));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example, how to call that function: