fengzifz.com

水则资车,旱则资舟

0%

PHP 判断 IP 段方法

封装了一个函数,用来判断某个 IP 是否在指定的 IP 段。例如:

$range 支持 3 种写法:

Wildcard

1
2
3
$ip = '192.168.1.203';
$range = '192.168.*.*';
ipInRange($ip, $range); // true

CIRD

1
2
3
$ip = '192.168.1.203';
$range = '192.168.1/24';
ipInRange($ip, $range); // true

开始-结束

1
2
3
$ip = '192.168.1.203';
$range = '192.168.1.1-192.168.1.255';
ipInRange($ip, $range); // true

以下是封装好的函数:

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
/**
* $range 支持多种写法
* - Wildcard: 1.2.3.*
* - CIRD:1.2.3/24 或者 1.2.3.4/255.255.255.0
* - Start-End: 1.2.3.0-1.2.3.255
* @param $ip
* @param $range
* @return bool
*/
public function ipInRange($ip, $range)
{
if (strpos($range, '/') !== false) {
// $range is in IP/NETMASK format
list($range, $netmask) = explode('/', $range, 2);
if (strpos($netmask, '.') !== false) {
// $netmask is a 255.255.0.0 format
$netmask = str_replace('*', '0', $netmask);
$netmask_dec = ip2long($netmask);
return ((ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec));
} else {
// $netmask is a CIDR size block
// fix the range argument
$x = explode('.', $range);
while (count($x) < 4) {
$x[] = '0';
}
list($a, $b, $c, $d) = $x;
$range = sprintf("%u.%u.%u.%u", empty($a) ? '0' : $a, empty($b) ? '0' : $b, empty($c) ? '0' : $c,
empty($d) ? '0' : $d);
$range_dec = ip2long($range);
$ip_dec = ip2long($ip);
# Strategy 1 - Create the netmask with 'netmask' 1s and then fill it to 32 with 0s
#$netmask_dec = bindec(str_pad('', $netmask, '1') . str_pad('', 32-$netmask, '0'));
# Strategy 2 - Use math to create it
$wildcard_dec = pow(2, (32 - $netmask)) - 1;
$netmask_dec = ~$wildcard_dec;
return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
}
} else {
// range might be 255.255.*.* or 1.2.3.0-1.2.3.255
if (strpos($range, '*') !== false) { // a.b.*.* format
// Just convert to A-B format by setting * to 0 for A and 255 for B
$lower = str_replace('*', '0', $range);
$upper = str_replace('*', '255', $range);
$range = "$lower-$upper";
}
if (strpos($range, '-') !== false) { // A-B format
list($lower, $upper) = explode('-', $range, 2);
$lower_dec = (float)sprintf("%u", ip2long($lower));
$upper_dec = (float)sprintf("%u", ip2long($upper));
$ip_dec = (float)sprintf("%u", ip2long($ip));
return (($ip_dec >= $lower_dec) && ($ip_dec <= $upper_dec));
}
return false;
}
}