2025-01-17 23:37:54 +00:00
|
|
|
import * as ipaddr from 'ipaddr.js'
|
|
|
|
|
import type { IPv4, IPv6 } from 'ipaddr.js';
|
2017-11-24 17:45:34 +00:00
|
|
|
|
2017-11-24 03:32:28 +00:00
|
|
|
export class IPAddress
|
|
|
|
|
{
|
2025-01-17 23:37:54 +00:00
|
|
|
public ip: IPv4 | IPv6 | null = null;
|
2017-11-24 17:45:34 +00:00
|
|
|
|
2025-01-17 23:37:54 +00:00
|
|
|
public constructor(buf?: Buffer | string, pos?: number)
|
2017-11-24 17:45:34 +00:00
|
|
|
{
|
2017-12-13 19:55:08 +00:00
|
|
|
try
|
2017-11-24 17:45:34 +00:00
|
|
|
{
|
2017-12-13 19:55:08 +00:00
|
|
|
if (buf !== undefined && buf instanceof Buffer)
|
2017-11-24 17:45:34 +00:00
|
|
|
{
|
2017-12-13 19:55:08 +00:00
|
|
|
if (pos !== undefined)
|
|
|
|
|
{
|
2025-01-17 23:37:54 +00:00
|
|
|
const bytes = buf.subarray(pos, 4);
|
|
|
|
|
this.ip = ipaddr.fromByteArray(Array.from(bytes));
|
2017-12-13 19:55:08 +00:00
|
|
|
}
|
2025-01-17 23:37:54 +00:00
|
|
|
else if (typeof buf === 'string')
|
2017-11-24 17:45:34 +00:00
|
|
|
{
|
2017-12-13 19:55:08 +00:00
|
|
|
if (ipaddr.isValid(buf))
|
|
|
|
|
{
|
|
|
|
|
this.ip = ipaddr.parse(buf);
|
|
|
|
|
}
|
2018-10-12 14:34:43 +01:00
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
throw new Error('Invalid IP address');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-01-17 23:37:54 +00:00
|
|
|
else if (typeof buf === 'string')
|
2018-10-12 14:34:43 +01:00
|
|
|
{
|
|
|
|
|
if (ipaddr.isValid(buf))
|
|
|
|
|
{
|
|
|
|
|
this.ip = ipaddr.parse(buf);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
throw new Error('Invalid IP address');
|
2017-11-24 17:45:34 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-01-17 23:37:54 +00:00
|
|
|
catch (_ignore: unknown)
|
2017-12-13 19:55:08 +00:00
|
|
|
{
|
|
|
|
|
this.ip = ipaddr.parse('0.0.0.0');
|
|
|
|
|
}
|
2017-11-24 17:45:34 +00:00
|
|
|
}
|
2025-01-17 23:37:54 +00:00
|
|
|
|
|
|
|
|
public static zero(): IPAddress
|
|
|
|
|
{
|
|
|
|
|
return new IPAddress('0.0.0.0');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public toString = (): string =>
|
|
|
|
|
{
|
|
|
|
|
if (!this.ip)
|
|
|
|
|
{
|
|
|
|
|
return '';
|
|
|
|
|
}
|
|
|
|
|
return this.ip.toString();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public writeToBuffer(buf: Buffer, pos: number): void
|
2017-11-24 17:45:34 +00:00
|
|
|
{
|
2025-01-17 23:37:54 +00:00
|
|
|
if (!this.ip)
|
|
|
|
|
{
|
|
|
|
|
throw new Error('Invalid IP');
|
|
|
|
|
}
|
|
|
|
|
const bytes: number[] = this.ip.toByteArray();
|
2017-11-24 17:45:34 +00:00
|
|
|
buf.writeUInt8(bytes[0], pos++);
|
|
|
|
|
buf.writeUInt8(bytes[1], pos++);
|
|
|
|
|
buf.writeUInt8(bytes[2], pos++);
|
|
|
|
|
buf.writeUInt8(bytes[3], pos);
|
|
|
|
|
}
|
2017-11-24 03:32:28 +00:00
|
|
|
}
|