Validate And Classify IPv4 Addresses
Parse dotted-quad IPv4 addresses strictly, reject leading zeros, and classify private, loopback and link-local ranges.
Code
export function parseIPv4(address) {
if (typeof address !== "string") return null;
const parts = address.split(".");
if (parts.length !== 4) return null;
const octets = [];
for (const part of parts) {
if (!/^\d{1,3}$/.test(part)) return null;
if (part.length > 1 && part.startsWith("0")) return null;
const value = Number(part);
if (value > 255) return null;
octets.push(value);
}
return octets;
}
export function isValidIPv4(address) {
return parseIPv4(address) !== null;
}
export function isPrivateIPv4(address) {
const octets = parseIPv4(address);
if (!octets) return false;
const [a, b] = octets;
return a === 10
|| (a === 172 && b >= 16 && b <= 31)
|| (a === 192 && b === 168)
|| a === 127
|| (a === 169 && b === 254);
}How the snippet works
Validate And Classify IPv4 Addresses keeps everything in the functions parseIPv4, isValidIPv4 and isPrivateIPv4.
The file repeats itself only inside for (const part of parts).
Watch out for
- The guard
typeof address !== "string"short-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The primary signature is export function parseIPv4(address)
Import parseIPv4 from the file and call it — the rest of the code is implementation detail.
Statements that matter
if (part.length > 1 && part.startsWith("0")) return null;
if (typeof address !== "string") return null;
if (!/^\d{1,3}$/.test(part)) return null;
Interactive Tools for This Topic
CIDR to IP ListExpand an IPv4 CIDR block into its individual addresses, showing network, broadcast, total count, and a bounded list you can copy.IPv4 Subnet CalculatorCalculate network and broadcast addresses, netmask, wildcard, and usable host range from an IPv4 address in CIDR notation.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `parseIPv4`, `isValidIPv4`, `isPrivateIPv4` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.