Skip to content

Commit b1be84a

Browse files
committed
Make IPv6 parsing code compatible with Node 10
1 parent 1a60c4f commit b1be84a

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

packages/grpc-js/src/channelz.ts

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,7 @@ export function unregisterChannelzRef(ref: ChannelRef | SubchannelRef | ServerRe
393393
}
394394

395395
/**
396-
* Parses a single section of an IPv6 address as two bytes
396+
* Parse a single section of an IPv6 address as two bytes
397397
* @param addressSection A hexadecimal string of length up to 4
398398
* @returns The pair of bytes representing this address section
399399
*/
@@ -402,6 +402,21 @@ function parseIPv6Section(addressSection: string): [number, number] {
402402
return [numberValue / 256 | 0, numberValue % 256];
403403
}
404404

405+
/**
406+
* Parse a chunk of an IPv6 address string to some number of bytes
407+
* @param addressChunk Some number of segments of up to 4 hexadecimal
408+
* characters each, joined by colons.
409+
* @returns The list of bytes representing this address chunk
410+
*/
411+
function parseIPv6Chunk(addressChunk: string): number[] {
412+
if (addressChunk === '') {
413+
return [];
414+
}
415+
const bytePairs = addressChunk.split(':').map(section => parseIPv6Section(section));
416+
const result: number[] = [];
417+
return result.concat(...bytePairs);
418+
}
419+
405420
/**
406421
* Converts an IPv4 or IPv6 address from string representation to binary
407422
* representation
@@ -413,17 +428,17 @@ function ipAddressStringToBuffer(ipAddress: string): Buffer | null {
413428
return Buffer.from(Uint8Array.from(ipAddress.split('.').map(segment => Number.parseInt(segment))));
414429
} else if (isIPv6(ipAddress)) {
415430
let leftSection: string;
416-
let rightSection: string | null;
431+
let rightSection: string;
417432
const doubleColonIndex = ipAddress.indexOf('::');
418433
if (doubleColonIndex === -1) {
419434
leftSection = ipAddress;
420-
rightSection = null;
435+
rightSection = '';
421436
} else {
422437
leftSection = ipAddress.substring(0, doubleColonIndex);
423438
rightSection = ipAddress.substring(doubleColonIndex + 2);
424439
}
425-
const leftBuffer = Buffer.from(leftSection.split(':').map(segment => parseIPv6Section(segment)).flat());
426-
const rightBuffer = rightSection ? Buffer.from(rightSection.split(':').map(segment => parseIPv6Section(segment)).flat()) : Buffer.alloc(0);
440+
const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection));
441+
const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection));
427442
const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0);
428443
return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]);
429444
} else {

0 commit comments

Comments
 (0)