OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Check IPv4 address membership in canonical CIDR ranges with JavaScript

JavaScript

Report inclusive membership for saved address and canonical network pairs without DNS, socket access or changing firewall rules.

Code excerpt: Check IPv4 address membership in canonical CIDR ranges with JavaScript. Read the full recipe for code, sources and recorded test scope.

Report inclusive membership for saved address and canonical network pairs without DNS, socket access or changing firewall rules. Reads saved text only; never sends network requests.

Before you start

  • Save as recipe.cjs and run with Node.js 22: node recipe.cjs < input.txt. Supply no CLI arguments.
  • Each nonempty LF-separated record must be exactly ADDRESS NETWORK/PREFIX, with one ASCII space. Exactly empty lines are ignored; whitespace is not trimmed. CR, tabs, NUL, comments and non-ASCII characters are rejected.
  • IPv4 addresses must contain exactly four decimal octets from 0 through 255, with no leading zeros except the single digit 0. Prefixes must use canonical decimal spelling from 0 through 32. Networks with nonzero host bits are rejected rather than normalized.
  • Reads at most 65537 stdin bytes and rejects input exceeding 65536 bytes. Accepts at most 100 nonempty records.
  • Uses TextDecoder from node:util with fatal:true and ignoreBOM:true for strict UTF-8 decoding, followed by explicit leading BOM rejection.
  • Validates all input before emitting exactly one compact JSON object followed by LF. Output has only a checks array of objects containing address, cidr and boolean contains. Original spellings, order and duplicates are preserved; empty input produces {"checks":[]}. Success exits 0 with empty stderr.
  • Membership includes network and inclusive last addresses, including both /31 addresses and the sole /32 address. Arithmetic uses exact integers, powers of two and Math.floor without bitwise operations or host enumeration.
  • Invalid input, extra arguments, decoding errors and stdin read failures produce empty stdout, exactly error: invalid input followed by LF on stderr, and exit status 2.

Build and check

  1. Save the example as recipe.cjs.
  2. Create input.txt with records in the documented exact format.
  3. Run the documented command; inspect the JSON result.
  4. Exit 2 means rejected input; no partial successful output is emitted.

Limits to understand

  • Only node:fs and node:util are loaded, for bounded stdin reads and strict decoding. There is no file-path access, environment inspection, network access, DNS, subprocess execution, dependency use or firewall modification.
  • IPv4 membership only; no IPv6, hostnames, URL forms, wildcard masks, alternate netmask forms or silent normalization.
  • Membership makes no statement about routability, trust, reachability, security or device availability. Ranges include all bit patterns, not merely usable hosts; /0 covers 4294967296 addresses and /32 covers one.
  • Output-write and allocation failures are outside the input-error guarantee.
  • IPv4 text only; no DNS, sockets, IPv6, firewall configuration or security/routability assessment.
  • LF-only ASCII input, at most 65536 bytes and 100 nonempty records. Blank lines ignored; duplicates retained.
  • Network input must have zero host bits. Both network and inclusive last addresses count as members.

Run it

node recipe.cjs < input.txt

Example input

192.0.2.129 192.0.2.0/24

Expected output

{"checks":[{"address":"192.0.2.129","cidr":"192.0.2.0/24","contains":true}]}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

JavaScript example
'use strict';

const fs = require('node:fs');
const { TextDecoder } = require('node:util');

function invalid() {
  throw new Error('invalid input');
}

function parseIPv4(text) {
  const parts = text.split('.');
  if (parts.length !== 4) invalid();
  const octets = parts.map((part) => {
    if (!/^(0|[1-9][0-9]{0,2})$/.test(part)) invalid();
    const value = Number(part);
    if (value > 255) invalid();
    return value;
  });
  return octets[0] * 16777216 + octets[1] * 65536 + octets[2] * 256 + octets[3];
}

function readAndValidate() {
  if (process.argv.length !== 2) invalid();

  const buffer = Buffer.alloc(65537);
  let length = 0;
  while (length < buffer.length) {
    const count = fs.readSync(0, buffer, length, buffer.length - length, null);
    if (count === 0) break;
    length += count;
  }
  if (length > 65536) invalid();

  const decoder = new TextDecoder('utf-8', {
    fatal: true,
    ignoreBOM: true
  });
  const text = decoder.decode(buffer.subarray(0, length));
  if (text.startsWith('\uFEFF')) invalid();
  if (/[^0-9.\/ \n]/.test(text)) invalid();

  const checks = [];
  for (const line of text.split('\n')) {
    if (line === '') continue;
    if (checks.length >= 100) invalid();

    const match = /^([0-9]+(?:\.[0-9]+){3}) ([0-9]+(?:\.[0-9]+){3})\/([0-9]+)$/.exec(line);
    if (match === null || match[0] !== line) invalid();

    const addressText = match[1];
    const networkText = match[2];
    const prefixText = match[3];
    const address = parseIPv4(addressText);
    const networkAddress = parseIPv4(networkText);

    if (!/^(0|[1-9][0-9]?)$/.test(prefixText)) invalid();
    const prefix = Number(prefixText);
    if (prefix > 32) invalid();

    const size = 2 ** (32 - prefix);
    const network = Math.floor(networkAddress / size) * size;
    if (networkAddress !== network) invalid();
    const last = network + size - 1;

    checks.push({
      address: addressText,
      cidr: networkText + '/' + prefixText,
      contains: address >= network && address <= last
    });
  }

  return JSON.stringify({ checks }) + '\n';
}

function main() {
  let output;
  try {
    output = readAndValidate();
  } catch {
    process.stderr.write('error: invalid input\n', () => process.exit(2));
    return;
  }
  process.stdout.write(output);
}

main();
What to verify after running
  • Compare the supplied example with its expected output.
  • Check /0, /31 and /32, inclusive boundaries and malformed-input rejection.
  • Review the recorded test evidence before adapting the code.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 0.1.0 · Documentation reviewed 2026-10-18.

    The release gate requires six primary fixtures and 29 supplementary checks in the pinned offline runtime. Actual passing evidence must be recorded for this candidate before approval. This does not prove exhaustive correctness or portability to every runtime.