Skip to content

Instantly share code, notes, and snippets.

@acdibble
Created October 27, 2021 10:47
Show Gist options
  • Save acdibble/5013723b4bb9d09230847ffb0037910c to your computer and use it in GitHub Desktop.
Save acdibble/5013723b4bb9d09230847ffb0037910c to your computer and use it in GitHub Desktop.
export class IPv4 {
static from(input: string) {
const [, a, b, c, d] = /(\d+)\.(\d+)\.(\d+)\.(\d+)/.exec(input)!;
const address = ((Number(a) << 24) | (Number(b) << 16) | ((Number(c) << 8) | Number(d))) >>> 0;
console.log(address.toString());
console.log(address.toString(2));
console.log(address.toString(16));
return new IPv4(address);
}
constructor(private readonly value: number) {}
toString() {
return this[Symbol.toPrimitive]('string');
}
[Symbol.toPrimitive](hint: 'number'): number;
[Symbol.toPrimitive](hint: 'string'): string;
[Symbol.toPrimitive](hint: 'number' | 'string'): string | number | null {
if (hint === 'number') {
return this.value;
}
if (hint === 'string') {
return `${(this.value >> 24) & 0xff}.${(this.value >> 16) & 0xff}.${
(this.value >> 8) & 0xff
}.${this.value & 0xff}`;
}
console.log(hint);
return null;
}
}
export class CIDRBlock {
static parse(cidr: string) {
const variable = 32 - Number.parseInt(/\/(\d+)/.exec(cidr)![1]!, 10);
const address = IPv4.from(cidr);
let mask = 0;
for (let i = 0; i < variable; i++) {
mask |= (1 << i) >>> 0;
}
return { start: address, end: (address | mask) >>> 0, mask };
}
readonly start: IPv4;
readonly end: IPv4;
readonly mask: number;
constructor(address: string) {
const { start, end, mask } = CIDRBlock.parse(address);
this.start = start;
this.end = new IPv4(end);
this.mask = mask;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment