-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.php
71 lines (59 loc) · 1.47 KB
/
function.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
<?php
// 不带cache的查询函数
function ip_check($ip) {
$need = ip2long($ip);
$strIPs = file_get_contents(dirname(__FILE__) . '/ip_list.txt');
$strIPs = trim($strIPs);
$arrRules = explode(',', $strIPs);
$arrIPs = array();
foreach ($arrRules as $k => $v) {
$arr = explode('-', $v);
if (count($arr) == 1) $arr[1] = $arr[0];
$arrIPs[] = trim($arr[0]);
$arrIPs[] = trim($arr[1]);
}
foreach($arrIPs as $k => $ip) {
$arrIPs[$k] = ip2long($ip);
}
sort($arrIPs);
$key = in_scope($arrIPs, $need);
return $key;
}
function in_scope(&$arrIPs, $need){
$begin = 0;
$end = count($arrIPs) - 1;
$key = false;
while($begin <= $end) {
$mid = floor(($begin + $end) / 2);
// echo $mid, "\n";
if ($arrIPs[$mid] > $need) {
$end = $mid - 1;
} else if ($arrIPs[$mid] < $need) {
$begin = $mid + 1;
} else {
$key = $mid;
break;
}
}
if ($key !== false) {
return true;
} else {
$nearkey = $mid;
if ($need > $arrIPs[$nearkey]) {
$nearbegin = $nearkey + $nearkey % 2;
$nearend = $nearbegin + 1;
} else {
$nearend = $nearkey - (1 - $nearkey % 2);
$nearbegin = $nearend - 1;
}
// echo $arrIPs[$nearbegin], "\n" . $need . "\n", $arrIPs[$nearend], "\n";
// echo long2ip($arrIPs[$nearbegin]), "\n" . long2ip($need) . "\n", long2ip($arrIPs[$nearend]), "\n";
if ($nearbegin < 0 || $nearend > count($arrIPs)) {
return false;
}
if (!($need > $arrIPs[$nearbegin] && $need < $arrIPs[$nearend])) {
return false;
}
return true;
}
}