Validate And Classify IPv4 Addresses

Parse dotted-quad IPv4 addresses strictly, reject leading zeros, and classify private, loopback and link-local ranges.

JavascriptForm Validation

Code

javascriptsnippet
29 lines
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 early return when 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

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `parseIPv4`, `isValidIPv4`, `isPrivateIPv4` at load time.