Skip to content

Instantly share code, notes, and snippets.

@paulgalow
Last active December 31, 2019 08:17
Show Gist options
  • Save paulgalow/d33599630f139e600fd5a39a2dfec1bc to your computer and use it in GitHub Desktop.
Save paulgalow/d33599630f139e600fd5a39a2dfec1bc to your computer and use it in GitHub Desktop.
Check for internet connectivity using TCP
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);
});
});
}
@paulgalow
Copy link
Author

Example, how to call that function:

let isOnline;

checkTCP()
  .then(() => (isOnline = true))
  .catch(() => (isOnline = false))
  .finally(() => console.log({ isOnline }));

@paulgalow
Copy link
Author

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