forked from zoujingli/ip2region
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ip2Region.php
343 lines (320 loc) · 10.6 KB
/
Ip2Region.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
<?php
/**
* ip2region php seacher client class
*
* @author chenxin<[email protected]>
* @date 2015-10-29
*/
defined('INDEX_BLOCK_LENGTH') or define('INDEX_BLOCK_LENGTH', 12);
defined('TOTAL_HEADER_LENGTH') or define('TOTAL_HEADER_LENGTH', 8192);
class Ip2Region
{
/**
* db file handler
*/
private $dbFileHandler = null;
/**
* header block info
*/
private $HeaderSip = null;
private $HeaderPtr = null;
private $headerLen = 0;
/**
* super block index info
*/
private $firstIndexPtr = 0;
private $lastIndexPtr = 0;
private $totalBlocks = 0;
/**
* for memory mode only
* the original db binary string
*/
private $dbBinStr = null;
private $dbFile = null;
/**
* construct method
*
* @param string ip2regionFile
*/
public function __construct($ip2regionFile = null)
{
$this->dbFile = is_null($ip2regionFile) ? __DIR__ . '/ip2region.db' : $ip2regionFile;
}
/**
* all the db binary string will be loaded into memory
* then search the memory only and this will a lot faster than disk base search
* @Note:
* invoke it once before put it to public invoke could make it thread safe
*
* @param string $ip
* @return array|null
* @throws Exception
*/
public function memorySearch($ip)
{
//check and load the binary string for the first time
if ($this->dbBinStr == null) {
$this->dbBinStr = file_get_contents($this->dbFile);
if ($this->dbBinStr == false) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
$this->firstIndexPtr = self::getLong($this->dbBinStr, 0);
$this->lastIndexPtr = self::getLong($this->dbBinStr, 4);
$this->totalBlocks = ($this->lastIndexPtr - $this->firstIndexPtr) / INDEX_BLOCK_LENGTH + 1;
}
if (is_string($ip)) $ip = self::safeIp2long($ip);
//binary search to define the data
$l = 0;
$h = $this->totalBlocks;
$dataPtr = 0;
while ($l <= $h) {
$m = (($l + $h) >> 1);
$p = $this->firstIndexPtr + $m * INDEX_BLOCK_LENGTH;
$sip = self::getLong($this->dbBinStr, $p);
if ($ip < $sip) {
$h = $m - 1;
} else {
$eip = self::getLong($this->dbBinStr, $p + 4);
if ($ip > $eip) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($this->dbBinStr, $p + 8);
break;
}
}
}
//not matched just stop it here
if ($dataPtr == 0) return null;
//get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
return array(
'city_id' => self::getLong($this->dbBinStr, $dataPtr),
'region' => substr($this->dbBinStr, $dataPtr + 4, $dataLen - 4),
);
}
/**
* get the data block through the specified ip address or long ip numeric with binary search algorithm
*
* @param string ip
* @return mixed Array or NULL for any error
* @throws Exception
*/
public function binarySearch($ip)
{
//check and conver the ip address
if (is_string($ip)) $ip = self::safeIp2long($ip);
if ($this->totalBlocks == 0) {
//check and open the original db file
if ($this->dbFileHandler == null) {
$this->dbFileHandler = fopen($this->dbFile, 'r');
if ($this->dbFileHandler == false) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
}
fseek($this->dbFileHandler, 0);
$superBlock = fread($this->dbFileHandler, 8);
$this->firstIndexPtr = self::getLong($superBlock, 0);
$this->lastIndexPtr = self::getLong($superBlock, 4);
$this->totalBlocks = ($this->lastIndexPtr - $this->firstIndexPtr) / INDEX_BLOCK_LENGTH + 1;
}
//binary search to define the data
$l = 0;
$h = $this->totalBlocks;
$dataPtr = 0;
while ($l <= $h) {
$m = (($l + $h) >> 1);
$p = $m * INDEX_BLOCK_LENGTH;
fseek($this->dbFileHandler, $this->firstIndexPtr + $p);
$buffer = fread($this->dbFileHandler, INDEX_BLOCK_LENGTH);
$sip = self::getLong($buffer, 0);
if ($ip < $sip) {
$h = $m - 1;
} else {
$eip = self::getLong($buffer, 4);
if ($ip > $eip) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($buffer, 8);
break;
}
}
}
//not matched just stop it here
if ($dataPtr == 0) return null;
//get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
fseek($this->dbFileHandler, $dataPtr);
$data = fread($this->dbFileHandler, $dataLen);
return array(
'city_id' => self::getLong($data, 0),
'region' => substr($data, 4),
);
}
/**
* get the data block associated with the specified ip with b-tree search algorithm
* @Note: not thread safe
*
* @param string ip
* @return Mixed Array for NULL for any error
* @throws Exception
*/
public function btreeSearch($ip)
{
if (is_string($ip)) $ip = self::safeIp2long($ip);
//check and load the header
if ($this->HeaderSip == null) {
//check and open the original db file
if ($this->dbFileHandler == null) {
$this->dbFileHandler = fopen($this->dbFile, 'r');
if ($this->dbFileHandler == false) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
}
fseek($this->dbFileHandler, 8);
$buffer = fread($this->dbFileHandler, TOTAL_HEADER_LENGTH);
//fill the header
$idx = 0;
$this->HeaderSip = array();
$this->HeaderPtr = array();
for ($i = 0; $i < TOTAL_HEADER_LENGTH; $i += 8) {
$startIp = self::getLong($buffer, $i);
$dataPtr = self::getLong($buffer, $i + 4);
if ($dataPtr == 0) break;
$this->HeaderSip[] = $startIp;
$this->HeaderPtr[] = $dataPtr;
$idx++;
}
$this->headerLen = $idx;
}
//1. define the index block with the binary search
$l = 0;
$h = $this->headerLen;
$sptr = 0;
$eptr = 0;
while ($l <= $h) {
$m = (($l + $h) >> 1);
//perfetc matched, just return it
if ($ip == $this->HeaderSip[$m]) {
if ($m > 0) {
$sptr = $this->HeaderPtr[$m - 1];
$eptr = $this->HeaderPtr[$m];
} else {
$sptr = $this->HeaderPtr[$m];
$eptr = $this->HeaderPtr[$m + 1];
}
break;
}
//less then the middle value
if ($ip < $this->HeaderSip[$m]) {
if ($m == 0) {
$sptr = $this->HeaderPtr[$m];
$eptr = $this->HeaderPtr[$m + 1];
break;
} elseif ($ip > $this->HeaderSip[$m - 1]) {
$sptr = $this->HeaderPtr[$m - 1];
$eptr = $this->HeaderPtr[$m];
break;
}
$h = $m - 1;
} else {
if ($m == $this->headerLen - 1) {
$sptr = $this->HeaderPtr[$m - 1];
$eptr = $this->HeaderPtr[$m];
break;
} elseif ($ip <= $this->HeaderSip[$m + 1]) {
$sptr = $this->HeaderPtr[$m];
$eptr = $this->HeaderPtr[$m + 1];
break;
}
$l = $m + 1;
}
}
//match nothing just stop it
if ($sptr == 0) return null;
//2. search the index blocks to define the data
$blockLen = $eptr - $sptr;
fseek($this->dbFileHandler, $sptr);
$index = fread($this->dbFileHandler, $blockLen + INDEX_BLOCK_LENGTH);
$dataPtr = 0;
$l = 0;
$h = $blockLen / INDEX_BLOCK_LENGTH;
while ($l <= $h) {
$m = (($l + $h) >> 1);
$p = (int)($m * INDEX_BLOCK_LENGTH);
$sip = self::getLong($index, $p);
if ($ip < $sip) {
$h = $m - 1;
} else {
$eip = self::getLong($index, $p + 4);
if ($ip > $eip) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($index, $p + 8);
break;
}
}
}
//not matched
if ($dataPtr == 0) return null;
//3. get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
fseek($this->dbFileHandler, $dataPtr);
$data = fread($this->dbFileHandler, $dataLen);
return array(
'city_id' => self::getLong($data, 0),
'region' => substr($data, 4),
);
}
/**
* safe self::safeIp2long function
*
* @param string ip
*
* @return false|int|string
*/
public static function safeIp2long($ip)
{
$ip = ip2long($ip);
// convert signed int to unsigned int if on 32 bit operating system
if ($ip < 0 && PHP_INT_SIZE == 4) {
$ip = sprintf("%u", $ip);
}
return $ip;
}
/**
* read a long from a byte buffer
*
* @param string b
* @param integer offset
* @return int|string
*/
public static function getLong($b, $offset)
{
$val = (
(ord($b[$offset++])) |
(ord($b[$offset++]) << 8) |
(ord($b[$offset++]) << 16) |
(ord($b[$offset]) << 24)
);
// convert signed int to unsigned int if on 32 bit operating system
if ($val < 0 && PHP_INT_SIZE == 4) {
$val = sprintf("%u", $val);
}
return $val;
}
/**
* destruct method, resource destroy
*/
public function __destruct()
{
if ($this->dbFileHandler != null) {
fclose($this->dbFileHandler);
}
$this->dbBinStr = null;
$this->HeaderSip = null;
$this->HeaderPtr = null;
}
}