Created
September 16, 2012 23:53
-
-
Save sitedyno/3734874 to your computer and use it in GitHub Desktop.
ipcat experiment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
$csv = file_get_contents('https://raw.github.com/client9/ipcat/master/datacenters.csv'); | |
$rows = explode("\n", $csv); | |
foreach ($rows as $row) { | |
if (strlen($row) === 0 || $row[0] === '#') { | |
continue; | |
} | |
$parts = explode(',', $row); | |
$newrow = array( | |
'_ip0' => inet_pton($parts[0]), | |
'_ip1' => inet_pton($parts[1]), | |
'owner' => sprintf("%s", $parts[3]), | |
); | |
$keys[$newrow['_ip0']] = $newrow; | |
} | |
// add a fake ipv6 block | |
// 2620:0:2BD0:: - 2620:0:2BD0:FFFF:FFFF:FFFF:FFFF:FFFF | |
/*$keys[inet_pton('2620:0:2BD0::')] = array( | |
'_ip0' => inet_pton('2620:0:2BD0::'), | |
'_ip1' => inet_pton('2620:0:2BD0:FFFF:FFFF:FFFF:FFFF:FFFF'), | |
'owner' => 'CORNELL-V6', | |
);*/ | |
ksort($keys); | |
//echo "/* \$keys done with " . count($keys) . " entries */\n"; | |
$data = array(); | |
$last1 = null; | |
foreach ($keys as $k => $v) { | |
$i0 = $v['_ip0']; | |
$i1 = $v['_ip1']; | |
if ($i0 > $i1 || $last1 >= $i0) { | |
die("ordering failed\n"); | |
} | |
$last1 = $i1; | |
$data[] = $v; | |
} | |
//echo "/* \$data done with " . count($data) . " entries */\n"; | |
// autogenerate database | |
print <<<EOT | |
<?php | |
/* Autogenerated. Do not edit */ | |
class IpDbBinary { | |
public static function find(\$ip) { | |
\$haystack = self::\$db; | |
\$high = count(\$haystack) - 1; | |
\$low = 0; | |
while (\$high >= \$low) { | |
\$probe = floor((\$high + \$low) / 2); | |
\$row = \$haystack[\$probe]; | |
if (\$row['_ip0'] > \$ip) { | |
\$high = \$probe - 1; | |
} else if (\$row['_ip1'] < \$ip) { | |
\$low = \$probe + 1; | |
} else { | |
return \$row; | |
} | |
} | |
return null; | |
} | |
EOT; | |
print " static public \$db = array(\n"; | |
//print var_export($data, true); | |
foreach ($data as $key => $datum) { | |
$datum['_ip0'] = str_replace("'", "\'", $datum['_ip0']); | |
$datum['_ip1'] = str_replace("'", "\'", $datum['_ip1']); | |
print " $key => array(\n"; | |
print " '_ip0' => b'{$datum['_ip0']}',\n"; | |
print " '_ip1' => b'{$datum['_ip1']}',\n"; | |
print " 'owner' => '{$datum['owner']}'\n"; | |
print " ),\n"; | |
} | |
print " );\n"; | |
print "}\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment