Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
ipv4.js360 linesDownload Raw Back to dist
1"use strict";
2/* eslint-disable no-param-reassign */
3var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4    if (k2 === undefined) k2 = k;
5    var desc = Object.getOwnPropertyDescriptor(m, k);
6    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7      desc = { enumerable: true, get: function() { return m[k]; } };
8    }
9    Object.defineProperty(o, k2, desc);
10}) : (function(o, m, k, k2) {
11    if (k2 === undefined) k2 = k;
12    o[k2] = m[k];
13}));
14var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15    Object.defineProperty(o, "default", { enumerable: true, value: v });
16}) : function(o, v) {
17    o["default"] = v;
18});
19var __importStar = (this && this.__importStar) || function (mod) {
20    if (mod && mod.__esModule) return mod;
21    var result = {};
22    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23    __setModuleDefault(result, mod);
24    return result;
25};
26Object.defineProperty(exports, "__esModule", { value: true });
27exports.Address4 = void 0;
28const common = __importStar(require("./common"));
29const constants = __importStar(require("./v4/constants"));
30const address_error_1 = require("./address-error");
31/**
32 * Represents an IPv4 address
33 * @class Address4
34 * @param {string} address - An IPv4 address string
35 */
36class Address4 {
37    constructor(address) {
38        this.groups = constants.GROUPS;
39        this.parsedAddress = [];
40        this.parsedSubnet = '';
41        this.subnet = '/32';
42        this.subnetMask = 32;
43        this.v4 = true;
44        /**
45         * Returns true if the address is correct, false otherwise
46         * @memberof Address4
47         * @instance
48         * @returns {Boolean}
49         */
50        this.isCorrect = common.isCorrect(constants.BITS);
51        /**
52         * Returns true if the given address is in the subnet of the current address
53         * @memberof Address4
54         * @instance
55         * @returns {boolean}
56         */
57        this.isInSubnet = common.isInSubnet;
58        this.address = address;
59        const subnet = constants.RE_SUBNET_STRING.exec(address);
60        if (subnet) {
61            this.parsedSubnet = subnet[0].replace('/', '');
62            this.subnetMask = parseInt(this.parsedSubnet, 10);
63            this.subnet = `/${this.subnetMask}`;
64            if (this.subnetMask < 0 || this.subnetMask > constants.BITS) {
65                throw new address_error_1.AddressError('Invalid subnet mask.');
66            }
67            address = address.replace(constants.RE_SUBNET_STRING, '');
68        }
69        this.addressMinusSuffix = address;
70        this.parsedAddress = this.parse(address);
71    }
72    static isValid(address) {
73        try {
74            // eslint-disable-next-line no-new
75            new Address4(address);
76            return true;
77        }
78        catch (e) {
79            return false;
80        }
81    }
82    /*
83     * Parses a v4 address
84     */
85    parse(address) {
86        const groups = address.split('.');
87        if (!address.match(constants.RE_ADDRESS)) {
88            throw new address_error_1.AddressError('Invalid IPv4 address.');
89        }
90        return groups;
91    }
92    /**
93     * Returns the correct form of an address
94     * @memberof Address4
95     * @instance
96     * @returns {String}
97     */
98    correctForm() {
99        return this.parsedAddress.map((part) => parseInt(part, 10)).join('.');
100    }
101    /**
102     * Converts a hex string to an IPv4 address object
103     * @memberof Address4
104     * @static
105     * @param {string} hex - a hex string to convert
106     * @returns {Address4}
107     */
108    static fromHex(hex) {
109        const padded = hex.replace(/:/g, '').padStart(8, '0');
110        const groups = [];
111        let i;
112        for (i = 0; i < 8; i += 2) {
113            const h = padded.slice(i, i + 2);
114            groups.push(parseInt(h, 16));
115        }
116        return new Address4(groups.join('.'));
117    }
118    /**
119     * Converts an integer into a IPv4 address object
120     * @memberof Address4
121     * @static
122     * @param {integer} integer - a number to convert
123     * @returns {Address4}
124     */
125    static fromInteger(integer) {
126        return Address4.fromHex(integer.toString(16));
127    }
128    /**
129     * Return an address from in-addr.arpa form
130     * @memberof Address4
131     * @static
132     * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address
133     * @returns {Adress4}
134     * @example
135     * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.)
136     * address.correctForm(); // '192.0.2.42'
137     */
138    static fromArpa(arpaFormAddress) {
139        // remove ending ".in-addr.arpa." or just "."
140        const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, '');
141        const address = leader.split('.').reverse().join('.');
142        return new Address4(address);
143    }
144    /**
145     * Converts an IPv4 address object to a hex string
146     * @memberof Address4
147     * @instance
148     * @returns {String}
149     */
150    toHex() {
151        return this.parsedAddress.map((part) => common.stringToPaddedHex(part)).join(':');
152    }
153    /**
154     * Converts an IPv4 address object to an array of bytes
155     * @memberof Address4
156     * @instance
157     * @returns {Array}
158     */
159    toArray() {
160        return this.parsedAddress.map((part) => parseInt(part, 10));
161    }
162    /**
163     * Converts an IPv4 address object to an IPv6 address group
164     * @memberof Address4
165     * @instance
166     * @returns {String}
167     */
168    toGroup6() {
169        const output = [];
170        let i;
171        for (i = 0; i < constants.GROUPS; i += 2) {
172            output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`);
173        }
174        return output.join(':');
175    }
176    /**
177     * Returns the address as a `bigint`
178     * @memberof Address4
179     * @instance
180     * @returns {bigint}
181     */
182    bigInt() {
183        return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join('')}`);
184    }
185    /**
186     * Helper function getting start address.
187     * @memberof Address4
188     * @instance
189     * @returns {bigint}
190     */
191    _startAddress() {
192        return BigInt(`0b${this.mask() + '0'.repeat(constants.BITS - this.subnetMask)}`);
193    }
194    /**
195     * The first address in the range given by this address' subnet.
196     * Often referred to as the Network Address.
197     * @memberof Address4
198     * @instance
199     * @returns {Address4}
200     */
201    startAddress() {
202        return Address4.fromBigInt(this._startAddress());
203    }
204    /**
205     * The first host address in the range given by this address's subnet ie
206     * the first address after the Network Address
207     * @memberof Address4
208     * @instance
209     * @returns {Address4}
210     */
211    startAddressExclusive() {
212        const adjust = BigInt('1');
213        return Address4.fromBigInt(this._startAddress() + adjust);
214    }
215    /**
216     * Helper function getting end address.
217     * @memberof Address4
218     * @instance
219     * @returns {bigint}
220     */
221    _endAddress() {
222        return BigInt(`0b${this.mask() + '1'.repeat(constants.BITS - this.subnetMask)}`);
223    }
224    /**
225     * The last address in the range given by this address' subnet
226     * Often referred to as the Broadcast
227     * @memberof Address4
228     * @instance
229     * @returns {Address4}
230     */
231    endAddress() {
232        return Address4.fromBigInt(this._endAddress());
233    }
234    /**
235     * The last host address in the range given by this address's subnet ie
236     * the last address prior to the Broadcast Address
237     * @memberof Address4
238     * @instance
239     * @returns {Address4}
240     */
241    endAddressExclusive() {
242        const adjust = BigInt('1');
243        return Address4.fromBigInt(this._endAddress() - adjust);
244    }
245    /**
246     * Converts a BigInt to a v4 address object
247     * @memberof Address4
248     * @static
249     * @param {bigint} bigInt - a BigInt to convert
250     * @returns {Address4}
251     */
252    static fromBigInt(bigInt) {
253        return Address4.fromHex(bigInt.toString(16));
254    }
255    /**
256     * Convert a byte array to an Address4 object
257     * @memberof Address4
258     * @static
259     * @param {Array<number>} bytes - an array of 4 bytes (0-255)
260     * @returns {Address4}
261     */
262    static fromByteArray(bytes) {
263        if (bytes.length !== 4) {
264            throw new address_error_1.AddressError('IPv4 addresses require exactly 4 bytes');
265        }
266        // Validate that all bytes are within valid range (0-255)
267        for (let i = 0; i < bytes.length; i++) {
268            if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {
269                throw new address_error_1.AddressError('All bytes must be integers between 0 and 255');
270            }
271        }
272        return this.fromUnsignedByteArray(bytes);
273    }
274    /**
275     * Convert an unsigned byte array to an Address4 object
276     * @memberof Address4
277     * @static
278     * @param {Array<number>} bytes - an array of 4 unsigned bytes (0-255)
279     * @returns {Address4}
280     */
281    static fromUnsignedByteArray(bytes) {
282        if (bytes.length !== 4) {
283            throw new address_error_1.AddressError('IPv4 addresses require exactly 4 bytes');
284        }
285        const address = bytes.join('.');
286        return new Address4(address);
287    }
288    /**
289     * Returns the first n bits of the address, defaulting to the
290     * subnet mask
291     * @memberof Address4
292     * @instance
293     * @returns {String}
294     */
295    mask(mask) {
296        if (mask === undefined) {
297            mask = this.subnetMask;
298        }
299        return this.getBitsBase2(0, mask);
300    }
301    /**
302     * Returns the bits in the given range as a base-2 string
303     * @memberof Address4
304     * @instance
305     * @returns {string}
306     */
307    getBitsBase2(start, end) {
308        return this.binaryZeroPad().slice(start, end);
309    }
310    /**
311     * Return the reversed ip6.arpa form of the address
312     * @memberof Address4
313     * @param {Object} options
314     * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix
315     * @instance
316     * @returns {String}
317     */
318    reverseForm(options) {
319        if (!options) {
320            options = {};
321        }
322        const reversed = this.correctForm().split('.').reverse().join('.');
323        if (options.omitSuffix) {
324            return reversed;
325        }
326        return `${reversed}.in-addr.arpa.`;
327    }
328    /**
329     * Returns true if the given address is a multicast address
330     * @memberof Address4
331     * @instance
332     * @returns {boolean}
333     */
334    isMulticast() {
335        return this.isInSubnet(new Address4('224.0.0.0/4'));
336    }
337    /**
338     * Returns a zero-padded base-2 string representation of the address
339     * @memberof Address4
340     * @instance
341     * @returns {string}
342     */
343    binaryZeroPad() {
344        return this.bigInt().toString(2).padStart(constants.BITS, '0');
345    }
346    /**
347     * Groups an IPv4 address for inclusion at the end of an IPv6 address
348     * @returns {String}
349     */
350    groupForV6() {
351        const segments = this.parsedAddress;
352        return this.address.replace(constants.RE_ADDRESS, `<span class="hover-group group-v4 group-6">${segments
353            .slice(0, 2)
354            .join('.')}</span>.<span class="hover-group group-v4 group-7">${segments
355            .slice(2, 4)
356            .join('.')}</span>`);
357    }
358}
359exports.Address4 = Address4;
360//# sourceMappingURL=ipv4.js.map
codekingpro/portable-devtools · Team Ai