OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Check IPv4 address membership in canonical CIDR ranges with Python

Python

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

Python code excerpt: Check IPv4 address membership in canonical CIDR ranges with Python. Version 0.1.0. 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

  • Run with Python 3.12, for example: python3.12 check_ipv4.py. Supply records through standard input and pass no CLI arguments. Only sys and json are imported.
  • Each nonempty line must be exactly ADDRESS NETWORK/PREFIX, with one ASCII space. Exactly empty lines are ignored; whitespace is never trimmed.
  • IPv4 octets must be canonical decimal values from 0 through 255. Prefixes must be canonical decimal values from 0 through 32. Leading zeros are forbidden except for the single digit 0.
  • Networks must have all host bits zero. Noncanonical networks reject the entire input rather than being normalized.
  • Success emits exactly one compact JSON object containing only checks, followed by LF, with exit status 0 and empty stderr. Results preserve record order, duplicates, and original valid spellings.
  • Membership includes both endpoints: /31 includes both addresses, /32 includes its exact address, and canonical 0.0.0.0/0 includes every IPv4 address.
  • Input errors produce empty stdout, exit status 2, and exactly error: invalid input followed by LF on stderr.

Build and check

  1. Save the example as recipe.py.
  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

  • Reads at most 65537 bytes once and rejects input longer than 65536 bytes. At most 100 nonempty records are accepted; empty input yields {"checks":[]}.
  • Requires strict UTF-8 without a leading BOM and ASCII-only records. CR, tabs, NUL, comments, extra spaces, and malformed records are rejected.
  • Uses bounded integer arithmetic without enumerating hosts. Range sizes include all bit patterns, not merely usable-host capacity; /0 has 4294967296 addresses and /32 has one.
  • Offline stdin/stdout processing only: no file access, environment inspection, network, DNS, subprocesses, dependencies, or firewall changes.
  • No IPv6, hostnames, URL forms, wildcard masks, netmask spellings, or implicit normalization. Results make no claims about routability, trust, reachability, security, or device availability.
  • 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

python3 recipe.py < 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.

Python example
import sys
import json


def decimal(token, max_digits, maximum):
    if not token or len(token) > max_digits:
        raise ValueError
    if len(token) > 1 and token[0] == '0':
        raise ValueError
    value = 0
    for char in token:
        if not ('0' <= char <= '9'):
            raise ValueError
        value = value * 10 + (ord(char) - ord('0'))
    if value > maximum:
        raise ValueError
    return value


def ipv4(token):
    parts = token.split('.')
    if len(parts) != 4:
        raise ValueError
    a, b, c, d = [decimal(part, 3, 255) for part in parts]
    return a * 16777216 + b * 65536 + c * 256 + d


def main():
    try:
        if len(sys.argv) != 1:
            raise ValueError
        raw = sys.stdin.buffer.read(65537)
        if len(raw) > 65536:
            raise ValueError
        text = raw.decode('utf-8', errors='strict')
        if text.startswith('\ufeff') or not text.isascii():
            raise ValueError

        checks = []
        for line in text.split('\n'):
            if line == '':
                continue
            if len(checks) >= 100:
                raise ValueError
            fields = line.split(' ')
            if len(fields) != 2:
                raise ValueError
            address_text, cidr_text = fields
            address = ipv4(address_text)
            cidr_parts = cidr_text.split('/')
            if len(cidr_parts) != 2:
                raise ValueError
            network_text, prefix_text = cidr_parts
            supplied_network = ipv4(network_text)
            prefix = decimal(prefix_text, 2, 32)
            size = 1 << (32 - prefix)
            network = (supplied_network // size) * size
            if supplied_network != network:
                raise ValueError
            last = network + size - 1
            checks.append({
                'address': address_text,
                'cidr': cidr_text,
                'contains': network <= address <= last
            })
    except Exception:
        sys.stderr.write('error: invalid input\n')
        return 2

    output = json.dumps({'checks': checks}, separators=(',', ':'))
    sys.stdout.write(output + '\n')
    return 0


if __name__ == '__main__':
    sys.exit(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.