From dc159e4404477a66ab3e1b301a4523c8e0dc80d5 Mon Sep 17 00:00:00 2001 From: Blake Matthes Date: Mon, 22 Dec 2025 11:34:11 -0600 Subject: [PATCH] feat(pingcheck): pings a sever and port to see if its up --- backend/src/utils/checkHost.utils.ts | 83 ++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 backend/src/utils/checkHost.utils.ts diff --git a/backend/src/utils/checkHost.utils.ts b/backend/src/utils/checkHost.utils.ts new file mode 100644 index 0000000..5286457 --- /dev/null +++ b/backend/src/utils/checkHost.utils.ts @@ -0,0 +1,83 @@ +import dns from "node:dns"; +import net from "node:net"; + +type IP = { + success: boolean; + message: string; +}; +export const checkHostnamePort = async (host: string): Promise => { + const [hostname, port] = host.split(":"); + + // a just incase to make sure we have the host name and port + if (!hostname || !port) { + return false; + } + + // Resolve the hostname to an IP address + const ip = (await checkHostUp(hostname)) as IP; + + if (!ip.success) { + return false; + } + const portNum = parseInt(port, 10); + + const hostUp = (await pingHost(hostname, portNum)) as IP; + + if (!hostUp.success) { + return false; + } + + return true; +}; + +const pingHost = (host: string, port: number) => { + return new Promise((res) => { + const s = new net.Socket(); + + s.setTimeout(2000); + + s.connect(port, host); + + s.on("connect", () => { + s.destroy(); + res({ + success: true, + message: "Server up", + }); + }); + + s.on("timeout", () => { + s.destroy(); + res({ + success: true, + message: "Server Offline or unreachable, please check connection", + }); + }); + + s.on("error", (e) => { + s.destroy(); + return res({ + success: false, + message: "Encountered error while checking if host:port up", + error: e, + }); + }); + }); +}; +const checkHostUp = (host: string) => { + return new Promise((res) => { + dns.lookup(host, (err, address) => { + if (err) { + return res({ + success: false, + message: "Error connecting to the server", + error: err, + }); + } else { + res({ success: true, message: "Server Ip", data: address }); + } + }); + }); +}; + +//checkHostnamePort("usmcd1vms036:1433");