From 40c6b80bb57d926b147191bd64caa729514f5af3 Mon Sep 17 00:00:00 2001 From: Markus Tacker Date: Thu, 8 Feb 2024 17:16:17 +0100 Subject: [PATCH] test: print resolved IP --- ip.test.ts | 11 +++++++++++ ip.ts | 26 ++++++++++++++++++++++++++ test.ts | 5 ++++- 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 ip.test.ts create mode 100644 ip.ts diff --git a/ip.test.ts b/ip.test.ts new file mode 100644 index 0000000..3598445 --- /dev/null +++ b/ip.test.ts @@ -0,0 +1,11 @@ +import { ipv4, ipv6 } from "./ip.ts"; +import { assertEquals } from "https://deno.land/std@0.208.0/assert/mod.ts"; + +Deno.test("ip.ts", async (t) => { + await t.step(`ipv4`, async () => + assertEquals(await ipv4("localhost"), ["127.0.0.1"]) + ); + await t.step(`ipv6`, async () => + assertEquals(await ipv6("localhost"), ["::1"]) + ); +}); diff --git a/ip.ts b/ip.ts new file mode 100644 index 0000000..18504dd --- /dev/null +++ b/ip.ts @@ -0,0 +1,26 @@ +const resolveHostname = + (recordType: "A" | "AAAA") => + async (hostname: string): Promise => { + const aRecords = await Deno.resolveDns(hostname, recordType); + if (aRecords.length > 0) return aRecords; + const cname = await Deno.resolveDns(hostname, "CNAME"); + const cnameIps = ( + await Promise.all( + cname.map((cname) => { + try { + return resolveHostname(recordType)(cname); + } catch { + return null; + } + }) + ) + ) + .flat() + .filter((ip): ip is string => ip !== null); + + if (cnameIps.length > 0) return cnameIps; + throw new Error(`Could not determine ${recordType} for ${hostname}!`); + }; + +export const ipv4 = resolveHostname("A"); +export const ipv6 = resolveHostname("AAAA"); diff --git a/test.ts b/test.ts index bf4b4d0..80a8185 100644 --- a/test.ts +++ b/test.ts @@ -1,5 +1,6 @@ import udp from "node:dgram"; import { assertEquals } from "https://deno.land/std@0.208.0/assert/mod.ts"; +import { ipv4, ipv6 } from "./ip.ts"; const hostname = Deno.env.get("HOSTNAME") ?? "localhost"; const proto = Deno.env.get("PROTO") ?? "udp4"; @@ -10,7 +11,9 @@ const port = 2444; Deno.test("UDP echo server", async (t) => { await t.step( - `the UDP server at ${hostname}:${port} (${proto}) should echo a given string`, + `the UDP server at ${hostname}:${port} (${( + await (proto === "udp6" ? ipv6 : ipv4)(hostname) + ).join(", ")}) should echo a given string`, async () => { const msg = `Hello World (${Date.now()})!`;