Skip to content

Commit

Permalink
[FIX] support IPv4 addresses mapped to IPv6 (#501)
Browse files Browse the repository at this point in the history
  • Loading branch information
aricart committed May 2, 2023
1 parent 0863710 commit 29229fb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
17 changes: 15 additions & 2 deletions nats-base-client/servers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ function isIPV6(hp: string) {
return !isIPV4OrHostname(hp);
}

function filterIpv6MappedToIpv4(hp: string): string {
const prefix = "::FFFF:";
const idx = hp.toUpperCase().indexOf(prefix);
if (idx !== -1 && hp.indexOf(".") !== -1) {
// we have something like: ::FFFF:127.0.0.1 or [::FFFF:127.0.0.1]:4222
let ip = hp.substring(idx + prefix.length);
ip = ip.replace("[", "");
return ip.replace("]", "");
}

return hp;
}

export function hostPort(
u: string,
): { listen: string; hostname: string; port: number } {
Expand All @@ -50,13 +63,13 @@ export function hostPort(
if (u.match(/^(.*:\/\/)(.*)/m)) {
u = u.replace(/^(.*:\/\/)(.*)/gm, "$2");
}

// in web environments, URL may not be a living standard
// that means that protocols other than HTTP/S are not
// parsable correctly.

// the third complication is that we may have been given
// an IPv6
// an IPv6 or worse IPv6 mapping an Ipv4
u = filterIpv6MappedToIpv4(u);

// we only wrap cases where they gave us a plain ipv6
// and we are not already bracketed
Expand Down
7 changes: 7 additions & 0 deletions tests/basics_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1253,3 +1253,10 @@ Deno.test("basics - msg typed payload", async () => {

await cleanup(ns, nc);
});

Deno.test("basics - ipv4 mapped to ipv6", async () => {
const ns = await NatsServer.start({ port: 4222 });
const nc = await connect({ servers: [`::ffff:127.0.0.1`] });
const nc2 = await connect({ servers: [`[::ffff:127.0.0.1]:${ns.port}`] });
await cleanup(ns, nc, nc2);
});

0 comments on commit 29229fb

Please sign in to comment.