Permalink
Browse files

Add IpDb generator

  • Loading branch information...
1 parent 173506c commit 0dec6d5bf551fa64890edada92bdbaed739d371f @ngalbreath ngalbreath committed May 24, 2012
Showing with 73 additions and 0 deletions.
  1. +73 −0 IpDbGenerate.php
View
@@ -0,0 +1,73 @@
+#!/usr/bin/env php
+<?php
+
+/*
+ * Now load in external datacenter list
+ */
+$rowstr = file_get_contents('https://raw.github.com/client9/ipcat/master/datacenters.csv');
+$rows = explode("\n", $rowstr);
+foreach ($rows as $row) {
+ if (strlen($row) == 0 || $row[0] == '#') {
+ continue;
+ }
+ $parts = explode(',', $row);
+
+ $newrow= array(
+ '_ip0' => ip2long($parts[0]),
+ '_ip1' => ip2long($parts[1]),
+ 'owner' => sprintf("%s", $parts[3]),
+ );
+ $keys[$newrow['_ip0']] = $newrow;
+}
+
+
+ksort($keys);
+
+$ary = array();
+
+$last0 = 0;
+$last1 = 0;
+foreach ($keys as $k => $v) {
+ $i0 = $v['_ip0'];
+ $i1 = $v['_ip1'];
+
+ // safety checks to make sure data is sorted correctly
+ if ($i0 == 0 || $i1 == 0 || $i0 > $i1 || $last1 >= $i0) {
+ print_r($v);
+ die;
+ }
+ $ary[] = $v;
+}
+
+// autogenerate database
+print <<<EOT
+<?php
+/* Autogenerated. Do not edit */
+class IpDb {
+ public static function find(\$ipstr) {
+ \$ip = ip2long(\$ipstr);
+ \$haystack = self::\$db;
+ \$high = count(\$haystack) -1;
+ \$low = 0;
+ while (\$high >= \$low) {
+ \$probe = floor((\$high + \$low) / 2);
+ \$row = \$haystack[\$probe];
+ \$a = \$row['_ip0'];
+ \$b = \$row['_ip1'];
+
+ if (\$a > \$ip) {
+ \$high = \$probe - 1;
+ } else if (\$b < \$ip) {
+ \$low = \$probe + 1;
+ } else {
+ return \$row;
+ }
+ }
+ return null;
+ }
+
+EOT;
+print " static public \$db = ";
+print var_export($ary, TRUE);
+print ";\n";
+print "}\n";

0 comments on commit 0dec6d5

Please sign in to comment.