phpで NetRange(ネット範囲) から CIDR(サブネットマスク)変換

whoisで取得できる値がNetRange(ネット範囲)形式だったりするので、iptablesとかで使えるようにCIDRに変換するプログラムを作る。

<?php

$lines=file("php://stdin");
foreach($lines as $line){
echo preg_replace_callback(
  '|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|',
  create_function(
    '$matches',
    'return $matches[1]."/".(32-log((ip2long($matches[2])+1 - ip2long($matches[1])),2));'
  ),$line
);
}

使い方

whois xxx.xxx.xxx.xxx|php netrange.php