/** * Varaxon subnet calculator: IPv4 and IPv6 subnet maths, VLSM planning and * range-to-CIDR, with no dependencies. It runs entirely in the browser on * varaxontech.com/subnet-calculator; nothing is sent to a server. * * MIT License * * Copyright (c) 2026 Varaxon Technologies LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // --------------------------------------------------------------------------- // IPv4 // --------------------------------------------------------------------------- /** Parses dotted-quad IPv4 ("10.0.0.1") to an unsigned 32-bit number, or null. */ export function parseIPv4(text: string): number | null { const parts = text.trim().split("."); if (parts.length !== 4) return null; let n = 0; for (const p of parts) { if (!/^\d{1,3}$/.test(p)) return null; const v = Number(p); if (v > 255) return null; n = n * 256 + v; } return n; } export function formatIPv4(n: number): string { return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join("."); } /** The netmask for a prefix length, as an unsigned 32-bit number. */ export function prefixToMask(prefix: number): number { return prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0; } /** Prefix length for a dotted netmask, or null if the mask is not contiguous. */ export function maskToPrefix(mask: string): number | null { const n = parseIPv4(mask); if (n === null) return null; for (let p = 0; p <= 32; p++) if (prefixToMask(p) === n) return p; return null; } export type IPv4Type = | "Private (RFC 1918)" | "Shared address space / CGNAT (RFC 6598)" | "Loopback" | "Link-local (APIPA)" | "Multicast" | "Documentation (RFC 5737)" | "Reserved" | "This network" | "Public"; function inRange4(ip: number, base: string, prefix: number): boolean { const mask = prefixToMask(prefix); return ((ip & mask) >>> 0) === parseIPv4(base); } export function ipv4Type(ip: number): IPv4Type { if (inRange4(ip, "10.0.0.0", 8) || inRange4(ip, "172.16.0.0", 12) || inRange4(ip, "192.168.0.0", 16)) return "Private (RFC 1918)"; if (inRange4(ip, "100.64.0.0", 10)) return "Shared address space / CGNAT (RFC 6598)"; if (inRange4(ip, "127.0.0.0", 8)) return "Loopback"; if (inRange4(ip, "169.254.0.0", 16)) return "Link-local (APIPA)"; if (inRange4(ip, "224.0.0.0", 4)) return "Multicast"; if (inRange4(ip, "192.0.2.0", 24) || inRange4(ip, "198.51.100.0", 24) || inRange4(ip, "203.0.113.0", 24)) return "Documentation (RFC 5737)"; if (inRange4(ip, "0.0.0.0", 8)) return "This network"; if (inRange4(ip, "240.0.0.0", 4)) return "Reserved"; return "Public"; } /** The historical class (A to E) of an address, from its first octet. */ export function ipv4Class(ip: number): "A" | "B" | "C" | "D" | "E" { const first = ip >>> 24; if (first < 128) return "A"; if (first < 192) return "B"; if (first < 224) return "C"; if (first < 240) return "D"; return "E"; } export type IPv4Info = { version: 4; address: string; prefix: number; cidr: string; network: string; broadcast: string; firstHost: string; lastHost: string; netmask: string; wildcard: string; binaryMask: string; binaryAddress: string; totalAddresses: number; usableHosts: number; ipClass: string; type: IPv4Type; reverseZone: string; }; function toBinary4(n: number): string { return n .toString(2) .padStart(32, "0") .replace(/(.{8})(?=.)/g, "$1."); } export function ipv4Info(ip: number, prefix: number): IPv4Info { const mask = prefixToMask(prefix); const network = (ip & mask) >>> 0; const broadcast = (network | (~mask >>> 0)) >>> 0; const total = 2 ** (32 - prefix); // RFC 3021: a /31 has two usable addresses (point-to-point); a /32 is one host. const usable = prefix >= 31 ? total : total - 2; const first = prefix >= 31 ? network : network + 1; const last = prefix >= 31 ? broadcast : broadcast - 1; const octets = Math.max(1, Math.floor(prefix / 8)); const reverseZone = formatIPv4(network).split(".").slice(0, octets).reverse().join(".") + ".in-addr.arpa"; return { version: 4, address: formatIPv4(ip), prefix, cidr: `${formatIPv4(network)}/${prefix}`, network: formatIPv4(network), broadcast: formatIPv4(broadcast), firstHost: formatIPv4(first), lastHost: formatIPv4(last), netmask: formatIPv4(mask), wildcard: formatIPv4(~mask >>> 0), binaryMask: toBinary4(mask), binaryAddress: toBinary4(ip), totalAddresses: total, usableHosts: usable, ipClass: ipv4Class(ip), type: ipv4Type(ip), reverseZone, }; } /** Splits a network into equal subnets of `newPrefix`, up to `limit` of them. */ export function splitIPv4( ip: number, prefix: number, newPrefix: number, limit = 256, ): { cidr: string; first: string; last: string; broadcast: string }[] { if (newPrefix < prefix || newPrefix > 32) return []; const network = (ip & prefixToMask(prefix)) >>> 0; const size = 2 ** (32 - newPrefix); const count = Math.min(2 ** (newPrefix - prefix), limit); const out = []; for (let i = 0; i < count; i++) { const info = ipv4Info(network + i * size, newPrefix); out.push({ cidr: info.cidr, first: info.firstHost, last: info.lastHost, broadcast: info.broadcast }); } return out; } /** Smallest prefix that fits `hosts` usable addresses (counting network and broadcast). */ export function prefixForHosts(hosts: number): number | null { if (!Number.isInteger(hosts) || hosts < 1) return null; if (hosts === 1) return 32; if (hosts === 2) return 31; for (let p = 30; p >= 0; p--) if (2 ** (32 - p) - 2 >= hosts) return p; return null; } export type VlsmRequest = { name: string; hosts: number }; export type VlsmAllocation = VlsmRequest & { cidr: string; netmask: string; firstHost: string; lastHost: string; broadcast: string; usableHosts: number; spare: number; }; /** * VLSM: carves a network into subnets sized for each request, largest first so * every block stays aligned. Returns allocations in the order requested. */ export function planVlsm( ip: number, prefix: number, requests: VlsmRequest[], ): { ok: true; allocations: VlsmAllocation[]; used: number; free: number } | { ok: false; error: string } { const network = (ip & prefixToMask(prefix)) >>> 0; const end = network + 2 ** (32 - prefix); const sized = requests.map((r, index) => ({ ...r, index, p: prefixForHosts(r.hosts) })); const bad = sized.find((r) => r.p === null); if (bad) return { ok: false, error: `"${bad.name}" needs a whole number of hosts, 1 or more.` }; const order = [...sized].sort((a, b) => (a.p as number) - (b.p as number) || a.index - b.index); let cursor = network; const placed = new Map(); for (const r of order) { const p = r.p as number; if (p < prefix) return { ok: false, error: `"${r.name}" needs ${r.hosts} hosts, more than the whole /${prefix}.` }; const size = 2 ** (32 - p); if (cursor % size !== 0) cursor = Math.ceil(cursor / size) * size; if (cursor + size > end) return { ok: false, error: `Not enough room: "${r.name}" (${r.hosts} hosts) does not fit in what is left of /${prefix}.` }; const info = ipv4Info(cursor, p); placed.set(r.index, { name: r.name, hosts: r.hosts, cidr: info.cidr, netmask: info.netmask, firstHost: info.firstHost, lastHost: info.lastHost, broadcast: info.broadcast, usableHosts: info.usableHosts, spare: info.usableHosts - r.hosts, }); cursor += size; } const used = cursor - network; return { ok: true, allocations: sized.map((r) => placed.get(r.index) as VlsmAllocation), used, free: end - network - used, }; } /** The fewest CIDR blocks that exactly cover an IPv4 range, inclusive. */ export function rangeToCidrs(start: number, end: number): string[] { if (start > end) return []; const out: string[] = []; let cur = start; while (cur <= end) { let size = 32; // Grow the block while it stays aligned and inside the range. while (size > 0) { const bigger = 2 ** (33 - size); if (cur % bigger !== 0 || cur + bigger - 1 > end) break; size--; } out.push(`${formatIPv4(cur)}/${size}`); cur += 2 ** (32 - size); } return out; } // --------------------------------------------------------------------------- // IPv6 // --------------------------------------------------------------------------- const MAX128 = (1n << 128n) - 1n; /** Parses IPv6 text (with "::" and an optional trailing IPv4) to a bigint, or null. */ export function parseIPv6(text: string): bigint | null { let s = text.trim().toLowerCase(); if (s.startsWith("[") && s.endsWith("]")) s = s.slice(1, -1); s = s.replace(/%.*$/, ""); // zone id if (!s.includes(":")) return null; // Trailing dotted IPv4 ("::ffff:192.0.2.1") becomes two hex groups. const v4 = s.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/); if (v4) { const n = parseIPv4(v4[2] ?? ""); if (n === null) return null; s = `${v4[1]}${(n >>> 16).toString(16)}:${(n & 0xffff).toString(16)}`; } const halves = s.split("::"); if (halves.length > 2) return null; const head = halves[0] ? halves[0].split(":") : []; const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : []; const groups = halves.length === 2 ? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail] : head; if (groups.length !== 8 || (halves.length === 2 && head.length + tail.length > 7)) return null; let n = 0n; for (const g of groups) { if (!/^[0-9a-f]{1,4}$/.test(g)) return null; n = (n << 16n) | BigInt(parseInt(g, 16)); } return n; } function groups6(n: bigint): number[] { const out: number[] = []; for (let i = 7; i >= 0; i--) out.push(Number((n >> BigInt(i * 16)) & 0xffffn)); return out; } /** Full form, all eight groups padded: 2001:0db8:0000:...:0001. */ export function expandIPv6(n: bigint): string { return groups6(n) .map((g) => g.toString(16).padStart(4, "0")) .join(":"); } /** RFC 5952 short form: lowercase, no leading zeros, longest zero run as "::". */ export function compressIPv6(n: bigint): string { const g = groups6(n); let bestStart = -1; let bestLen = 0; for (let i = 0; i < 8; ) { if (g[i] !== 0) { i++; continue; } let j = i; while (j < 8 && g[j] === 0) j++; if (j - i > bestLen) { bestStart = i; bestLen = j - i; } i = j; } const hex = g.map((x) => x.toString(16)); if (bestLen < 2) return hex.join(":"); return `${hex.slice(0, bestStart).join(":")}::${hex.slice(bestStart + bestLen).join(":")}`; } export function prefixToMask6(prefix: number): bigint { return prefix === 0 ? 0n : (MAX128 << BigInt(128 - prefix)) & MAX128; } export function ipv6Type(n: bigint): string { const within = (base: string, p: number) => (n & prefixToMask6(p)) === (parseIPv6(base) as bigint); if (n === 0n) return "Unspecified"; if (n === 1n) return "Loopback"; if (within("::ffff:0:0", 96)) return "IPv4-mapped"; if (within("2001:db8::", 32)) return "Documentation (RFC 3849)"; if (within("fe80::", 10)) return "Link-local"; if (within("fc00::", 7)) return "Unique local (ULA, private)"; if (within("ff00::", 8)) return "Multicast"; if (within("2002::", 16)) return "6to4"; if (within("2000::", 3)) return "Global unicast (public)"; return "Reserved"; } /** 2^bits written out in full, with thousands separators. */ function powerOfTwo(bits: number): string { return (1n << BigInt(bits)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } export type IPv6Info = { version: 6; address: string; expanded: string; prefix: number; cidr: string; network: string; lastAddress: string; rangeStart: string; rangeEnd: string; totalAddresses: string; totalPower: string; subnets64: string; type: string; reverseZone: string; }; export function ipv6Info(ip: bigint, prefix: number): IPv6Info { const mask = prefixToMask6(prefix); const network = ip & mask; const last = network | (~mask & MAX128); const nibbles = Math.max(1, Math.floor(prefix / 4)); const reverseZone = expandIPv6(network).replace(/:/g, "").slice(0, nibbles).split("").reverse().join(".") + ".ip6.arpa"; return { version: 6, address: compressIPv6(ip), expanded: expandIPv6(ip), prefix, cidr: `${compressIPv6(network)}/${prefix}`, network: compressIPv6(network), lastAddress: compressIPv6(last), rangeStart: expandIPv6(network), rangeEnd: expandIPv6(last), totalAddresses: powerOfTwo(128 - prefix), totalPower: `2^${128 - prefix}`, subnets64: prefix <= 64 ? powerOfTwo(64 - prefix) : "0 (smaller than a /64)", type: ipv6Type(ip), reverseZone, }; } // --------------------------------------------------------------------------- // One input box for both // --------------------------------------------------------------------------- /** * Reads what people type: "192.168.1.10/24", "192.168.1.10 255.255.255.0", * "192.168.1.10/255.255.255.0", a bare IPv4 (/32), "2001:db8::1/48" or a bare * IPv6 (/128). Returns the calculated subnet or a plain-English error. */ export function calculate( input: string, ): { ok: true; info: IPv4Info | IPv6Info } | { ok: false; error: string } { const text = input.trim(); if (!text) return { ok: false, error: "Enter an IP address with a prefix, like 192.168.1.0/24." }; const [addr = "", rest, extra] = text.split(/\s*\/\s*|\s+/); if (extra !== undefined) return { ok: false, error: "Use one address and one prefix, like 10.0.0.0/16." }; if (addr.includes(":")) { const ip = parseIPv6(addr); if (ip === null) return { ok: false, error: `"${addr}" is not a valid IPv6 address.` }; const prefix = rest === undefined ? 128 : Number(rest); if (!/^\d{1,3}$/.test(rest ?? "128") || prefix > 128) return { ok: false, error: "An IPv6 prefix is a number from 0 to 128." }; return { ok: true, info: ipv6Info(ip, prefix) }; } const ip = parseIPv4(addr); if (ip === null) return { ok: false, error: `"${addr}" is not a valid IPv4 address.` }; let prefix = 32; if (rest !== undefined) { if (rest.includes(".")) { const p = maskToPrefix(rest); if (p === null) return { ok: false, error: `"${rest}" is not a valid subnet mask.` }; prefix = p; } else { prefix = Number(rest); if (!/^\d{1,2}$/.test(rest) || prefix > 32) return { ok: false, error: "An IPv4 prefix is a number from 0 to 32." }; } } return { ok: true, info: ipv4Info(ip, prefix) }; }