athlon1600/php-cidr-range-optimizer

Given a list of IP ranges, merge them into the smallest possible list of CIDRs.

v1.0.2 2024-08-16 19:26 UTC

This package is auto-updated.

Last update: 2024-10-16 20:05:51 UTC


README

Minimum PHP Version GitHub Workflow Status (with event)

Given a list of IP address ranges, minify that list to the smallest possible size by performing the following optimizations:

  • removing invalid IP addresses/ranges from the list
  • removing duplicates
  • removing IP ranges already covered by larger ranges in the list
  • merging adjacent IP ranges into larger, contiguous blocks

⭐ Demo

An online tool that uses a near exact version of this library:

Installation

composer require athlon1600/php-cidr-range-optimizer

Usage

Build your list of IP ranges into CIDRList object, then use RangeOptimizer class to optimize it. Example:

use ProxyNova\RangeOptimizer\CIDRList;
use ProxyNova\RangeOptimizer\RangeOptimizer;

$ranges = CIDRList::fromArray([
    "192.168.1.0/26",
    "192.168.1.64/27",
    "192.168.1.96/27",
    "10.1.0.0/26",
    "10.1.0.64/26"
]);

// returns new optimized CIDRList object
$optimized = RangeOptimizer::optimize($ranges);

echo $optimized;

Output:

10.1.0.0/25
192.168.1.0/25