-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBaseStation.php
73 lines (58 loc) · 1.86 KB
/
BaseStation.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
<?php
namespace ipip\datx;
/**
* IPIP datx code (https://www.ipip.net)
* 基站IP度
*
* @ $datx = new ipip\datx\BaseStation("c:/work/tiantexin/17mon/station_ip.datx");
* @ var_dump($datx->find("27.128.80.57"));
*/
class BaseStation
{
private $file;
private $offset;
private $index;
public function __construct($path)
{
$this->file = fopen($path, 'rb');
$this->offset = unpack('Nlen', fread($this->file, 4));
$this->index = fread($this->file, $this->offset['len'] - 4);
}
/**
* @param string $ip
*
* @return bool|array|null
*/
public function find($ip)
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE)
{
return FALSE; // or throw Exception?
}
$ips = explode('.', $ip);
$nip = pack('N', ip2long($ip));
$idx = 256 * $ips[0] + intval($ips[1]);
$idx = $idx * 4;
$start = unpack('Vlen', substr($this->index, $idx, 4));
$off = NULL;
$len = NULL;
for ($start = $start['len'] * 13 + 262144; $start < $this->offset['len'] - 262148; $start += 13)
{
if ($nip >= ($this->index[$start] . $this->index[$start + 1] . $this->index[$start + 2] . $this->index[$start + 3]))
{
if ($nip <= ($this->index[$start + 4] . $this->index[$start + 5] . $this->index[$start + 6] . $this->index[$start + 7]))
{
$off = unpack('Vlen', substr($this->index, $start + 8, 4));
$len = unpack('Clen', $this->index[$start + 12]);
break;
}
}
}
if ($off === NULL)
{
return NULL;
}
fseek($this->file, $this->offset['len'] + $off['len'] - 262144);
return explode("\t", fread($this->file, $len['len']));
}
}