From 1a60c4f3a92d6c0559422666ec446bdc3b0f70a3 Mon Sep 17 00:00:00 2001 From: Michael Lumish Date: Thu, 4 Nov 2021 14:11:16 -0700 Subject: [PATCH] grpc-js: channelz: Fix algorithm for representing an IPv6 address in binary --- packages/grpc-js/src/channelz.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/grpc-js/src/channelz.ts b/packages/grpc-js/src/channelz.ts index 768efaa58..94d84d8f2 100644 --- a/packages/grpc-js/src/channelz.ts +++ b/packages/grpc-js/src/channelz.ts @@ -392,6 +392,16 @@ export function unregisterChannelzRef(ref: ChannelRef | SubchannelRef | ServerRe } } +/** + * Parses a single section of an IPv6 address as two bytes + * @param addressSection A hexadecimal string of length up to 4 + * @returns The pair of bytes representing this address section + */ +function parseIPv6Section(addressSection: string): [number, number] { + const numberValue = Number.parseInt(addressSection, 16); + return [numberValue / 256 | 0, numberValue % 256]; +} + /** * Converts an IPv4 or IPv6 address from string representation to binary * representation @@ -412,8 +422,8 @@ function ipAddressStringToBuffer(ipAddress: string): Buffer | null { leftSection = ipAddress.substring(0, doubleColonIndex); rightSection = ipAddress.substring(doubleColonIndex + 2); } - const leftBuffer = Uint8Array.from(leftSection.split(':').map(segment => Number.parseInt(segment, 16))); - const rightBuffer = rightSection ? Uint8Array.from(rightSection.split(':').map(segment => Number.parseInt(segment, 16))) : new Uint8Array(); + const leftBuffer = Buffer.from(leftSection.split(':').map(segment => parseIPv6Section(segment)).flat()); + const rightBuffer = rightSection ? Buffer.from(rightSection.split(':').map(segment => parseIPv6Section(segment)).flat()) : Buffer.alloc(0); const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); } else {