Skip to content

Instantly share code, notes, and snippets.

@paulgalow

paulgalow/checkTCP.js

Last active Dec 31, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@paulgalow paulgalow commented Dec 31, 2019

Example, how to call that function:

let isOnline;

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

This comment has been minimized.

Copy link
Owner Author

@paulgalow paulgalow commented Dec 31, 2019

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
You can’t perform that action at this time.