OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Check IP membership in a strict CIDR network without network access

Python

Classify IP addresses against an explicitly supplied network.

Python code excerpt: Check IP membership in a strict CIDR network without network access. Version 1.0.0. Read the full recipe for code, sources and recorded test scope.

Classify IP addresses against an explicitly supplied network. This stdin-based Python CLI processes one bounded JSON request and returns the documented JSON result. It does not execute jobs or contact external services. Inspect its limits before adapting it to an application.

Before you start

  • Python 3.12 standard library; no third-party packages. Verified with the recorded pinned runtime.
  • One UTF-8 JSON object on stdin, no command-line arguments. Maximum encoded request size is 20000 bytes.

Build and check

  1. Save the source as check-cidr-membership-python.py.
  2. Save the example JSON below as request.json.
  3. Run python3 check-cidr-membership-python.py < request.json.
  4. Compare the parsed JSON result with the expected output. Invalid input exits 2 with empty stdout and a generic stderr message.

Limits to understand

  • Membership is not authorization and does not establish reachability or permission to access any resource.
  • Only literal IPv4 and IPv6 addresses are supported; hostnames, scope identifiers, whitespace and networks with host bits set are rejected.
  • Mixed IP versions are accepted, but addresses of a different version from the network always produce false. IPv4-mapped IPv6 addresses remain IPv6 addresses.
  • Uses only the Python standard library and stdin/stdout, with generic stderr output for invalid input; it performs no DNS lookups, network access or firewall changes.
  • Input exactly {"network":string,"addresses":array of at most 500 strings}. Require a slash and an ASCII decimal prefix length in network; use ipaddress.ip_network(strict=True). Reject host bits, whitespace, scope identifiers (%), hostnames and non-string addresses.
  • Parse addresses using ipaddress.ip_address. Mixed address versions are valid and membership is false for the other version. Preserve address order and duplicates.
  • Output {"network":canonical with_prefixlen string,"members":array of booleans}. No DNS, network calls or firewall changes. Document that membership is not authorization.
  • The complete encoded input is limited to 20000 bytes; one additional byte can be read to detect overflow.
  • This is a bounded local helper. Passing the recorded cases does not verify every input, every Python version or an external integration.

Run it

python3 check-cidr-membership-python.py < request.json

Example input

{"network": "192.0.2.0/24", "addresses": ["192.0.2.0", "192.0.2.255", "192.0.3.1", "::1"]}

Expected output

{"network":"192.0.2.0/24","members":[true,true,false,false]}
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 ipaddress
import json
import math
import sys


def reject_constant(_):
    raise ValueError()


def finite_float(text):
    value = float(text)
    if not math.isfinite(value):
        raise ValueError()
    return value


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError()
        result[key] = value
    return result


def check_unicode(root):
    pending = [root]
    while pending:
        value = pending.pop()
        if isinstance(value, str):
            if any(0xD800 <= ord(c) <= 0xDFFF for c in value):
                raise ValueError()
        elif isinstance(value, dict):
            pending.extend(value.keys())
            pending.extend(value.values())
        elif isinstance(value, list):
            pending.extend(value)


def clean_ip_text(value):
    if not isinstance(value, str):
        raise ValueError()
    if '%' in value or any(c.isspace() for c in value):
        raise ValueError()
    return value


def process():
    if len(sys.argv) != 1:
        raise ValueError()
    raw = sys.stdin.buffer.read(20001)
    if len(raw) > 20000:
        raise ValueError()
    data = json.loads(
        raw.decode('utf-8', errors='strict'),
        object_pairs_hook=unique_object,
        parse_constant=reject_constant,
        parse_float=finite_float,
    )
    check_unicode(data)
    if not isinstance(data, dict) or set(data) != {'network', 'addresses'}:
        raise ValueError()

    network_text = clean_ip_text(data['network'])
    if network_text.count('/') != 1:
        raise ValueError()
    _, prefix = network_text.split('/')
    if not prefix or any(c < '0' or c > '9' for c in prefix):
        raise ValueError()
    network = ipaddress.ip_network(network_text, strict=True)

    addresses = data['addresses']
    if not isinstance(addresses, list) or len(addresses) > 500:
        raise ValueError()
    members = []
    for text in addresses:
        address = ipaddress.ip_address(clean_ip_text(text))
        members.append(address.version == network.version and address in network)
    return {'network': network.with_prefixlen, 'members': members}


def main():
    try:
        result = process()
    except (ValueError, TypeError, RecursionError, OverflowError):
        sys.stderr.write('Invalid input\n')
        return 2
    sys.stdout.write(json.dumps(result, separators=(',', ':')) + '\n')
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • Run the documented example and compare the JSON result.
  • Confirm malformed requests exit 2 without copying input data into diagnostic messages.
  • 21 independent CLI cases passed on this exact source, including an unexpected-argument check.

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 1.0.0 · Documentation reviewed 2026-11-18.

    21 recorded CLI cases passed in rootless Docker on the pinned Python 3.12 runtime, with 512 MiB RAM, 1 CPU, no network, and read-only source. Other runtimes and all possible inputs are not verified.