Skip to content

Commit

Permalink
test: print resolved IP
Browse files Browse the repository at this point in the history
  • Loading branch information
coderbyheart committed Feb 8, 2024
1 parent 3d7d8b8 commit 40c6b80
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
11 changes: 11 additions & 0 deletions ip.test.ts
Original file line number Diff line number Diff line change
@@ -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"])
);
});
26 changes: 26 additions & 0 deletions ip.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const resolveHostname =
(recordType: "A" | "AAAA") =>
async (hostname: string): Promise<string[]> => {
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");
5 changes: 4 additions & 1 deletion test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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()})!`;

Expand Down

0 comments on commit 40c6b80

Please sign in to comment.