This repository has been archived by the owner on Feb 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
/
IpDbGenerate.php
executable file
·71 lines (63 loc) · 1.57 KB
/
IpDbGenerate.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/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;
}
$last0 = $i0;
$last1 = $i1;
$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];
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 = ";
print var_export($ary, TRUE);
print ";\n";
print "}\n";