|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Jasny; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Check if IP address is in CIDR block |
|
7
|
|
|
* |
|
8
|
|
|
* @param string $ip |
|
9
|
|
|
* @param string $cidr |
|
10
|
|
|
* @return boolean |
|
11
|
|
|
*/ |
|
12
|
|
|
function ip_in_cidr($ip, $cidr) |
|
13
|
|
|
{ |
|
14
|
1 |
|
if ($cidr === '0.0.0.0/0' || $cidr === '::/0' || $cidr === '::') return true; |
|
15
|
|
|
|
|
16
|
1 |
|
$ipv = strpos($ip, ':') === false ? 4 : 6; |
|
17
|
1 |
|
$cidrv = strpos($cidr, ':') === false ? 4 : 6; |
|
18
|
|
|
|
|
19
|
1 |
|
if ($ipv !== $cidrv) return false; |
|
20
|
|
|
|
|
21
|
1 |
|
$fn = __NAMESPACE__ . "\\ipv{$ipv}_in_cidr"; |
|
22
|
1 |
|
return $fn($ip, $cidr); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Check if IPv4 address is in CIDR block |
|
27
|
|
|
* |
|
28
|
|
|
* @param string $ip |
|
29
|
|
|
* @param string $cidr |
|
30
|
|
|
* @return boolean |
|
31
|
|
|
*/ |
|
32
|
|
|
function ipv4_in_cidr($ip, $cidr) |
|
33
|
|
|
{ |
|
34
|
2 |
|
list($subnet, $mask) = explode('/', $cidr); |
|
35
|
|
|
|
|
36
|
2 |
|
$ipMasked = ip2long($ip) & ~((1 << (32 - $mask)) - 1); |
|
37
|
2 |
|
$subnetMasked = ip2long($subnet) & ~((1 << (32 - $mask)) - 1); |
|
38
|
|
|
|
|
39
|
2 |
|
return $ipMasked == $subnetMasked; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Converts inet_pton output to string with bits |
|
44
|
|
|
* |
|
45
|
|
|
* @param string $inet |
|
46
|
|
|
* @return string |
|
47
|
|
|
*/ |
|
48
|
|
|
function inet_to_bits($inet) |
|
49
|
|
|
{ |
|
50
|
2 |
|
$unpacked = unpack('A16', $inet); |
|
|
|
|
|
|
51
|
2 |
|
$unpacked = str_split($unpacked[1]); |
|
|
|
|
|
|
52
|
2 |
|
$binaryip = ''; |
|
|
|
|
|
|
53
|
|
|
|
|
54
|
2 |
|
foreach ($unpacked as $char) { |
|
|
|
|
|
|
55
|
2 |
|
$binaryip .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT); |
|
56
|
2 |
|
} |
|
|
|
|
|
|
57
|
|
|
|
|
58
|
2 |
|
return $binaryip; |
|
|
|
|
|
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Check if IPv6 address is in CIDR block |
|
63
|
|
|
* |
|
64
|
|
|
* @param string $ip |
|
65
|
|
|
* @param string $cidr |
|
66
|
|
|
* @return boolean |
|
67
|
|
|
*/ |
|
68
|
|
|
function ipv6_in_cidr($ip, $cidr) |
|
69
|
|
|
{ |
|
70
|
2 |
|
$inetIp = inet_pton($ip); |
|
71
|
2 |
|
$binaryIp = inet_to_bits($inetIp); |
|
72
|
|
|
|
|
73
|
2 |
|
if (strpos($cidr, '/') === false) { |
|
74
|
1 |
|
$net = $cidr; |
|
75
|
1 |
|
$mask = $cidr === '::' ? 0 : substr_count(rtrim($cidr, ':'), ':') * 16; |
|
76
|
1 |
|
} else { |
|
77
|
2 |
|
list($net, $mask) = explode('/', $cidr); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
2 |
|
$inetNet = inet_pton($net); |
|
81
|
2 |
|
$binaryNet = inet_to_bits($inetNet); |
|
82
|
|
|
|
|
83
|
2 |
|
$ipNetBits = substr($binaryIp, 0, $mask); |
|
84
|
2 |
|
$netBits = substr($binaryNet, 0, $mask); |
|
85
|
|
|
|
|
86
|
2 |
|
return $ipNetBits === $netBits; |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
|
|
|