Skip to content

Instantly share code, notes, and snippets.

@kitelife
Last active May 25, 2016 09:44
Show Gist options
  • Save kitelife/2e53011c33a00d026ae519ecf47bf510 to your computer and use it in GitHub Desktop.
Save kitelife/2e53011c33a00d026ae519ecf47bf510 to your computer and use it in GitHub Desktop.
<?php
function checkIPClass($ip) {
$ipLong = ip2long($ip);
if ($ipLong == -1 || $ipLong === FALSE) {
return null;
}
$ipBinaryString = sprintf('%b', $ipLong);
$ipBinaryString = str_pad($ipBinaryString, 32, '0', STR_PAD_LEFT);
$whichClass = null;
$classFeatureMapper = array(
// A类ip
'0' => 'A',
// B类ip
'10' => 'B',
// C类ip
'110' => 'C',
// D类ip
'1110' => 'D',
// E类ip
'1111' => 'E',
);
foreach ($classFeatureMapper as $feature => $ipClass) {
if (strpos($ipBinaryString, '' . $feature) === 0) {
$whichClass = $ipClass;
break;
}
}
return $whichClass;
}
$ipList = array(
"127.0.0.1",
"127.101.0.1",
"192.168.0.1",
"202.168.3.4",
"128.127.7.8",
"224.233.56.7",
);
$nodeList = array();
foreach ($ipList as $ip) {
$whichClass = checkIPClass($ip);
if ($whichClass === null) {
echo "$ip not in any class\n";
continue;
}
if (!array_key_exists($whichClass, $nodeList)) {
$nodeList[$whichClass] = array();
}
array_push($nodeList[$whichClass], $ip);
}
echo json_encode(array('nodes' => array_values($nodeList))) . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment