|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace artes\IP; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* A class for validating IP addresses. |
|
7
|
|
|
* |
|
8
|
|
|
* @SuppressWarnings(PHPMD) |
|
9
|
|
|
*/ |
|
10
|
|
|
class IP |
|
11
|
|
|
{ |
|
12
|
9 |
|
public function validip($ip) : bool |
|
13
|
|
|
{ |
|
14
|
9 |
|
if ($this->ipv4($ip) || $this->ipv6($ip)) { |
|
15
|
4 |
|
return true; |
|
16
|
|
|
} |
|
17
|
6 |
|
return false; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
10 |
|
public function ipv4($ip) : bool |
|
21
|
|
|
{ |
|
22
|
10 |
|
$ipv4 = "/^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/"; |
|
23
|
|
|
|
|
24
|
10 |
|
if (preg_match($ipv4, $ip)) { |
|
25
|
4 |
|
return true; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
7 |
|
return false; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
7 |
|
public function ipv6($ip) : bool |
|
32
|
|
|
{ |
|
33
|
7 |
|
$ipv6 = "/^(([0-9]|[a-f]|[A-F]){4}:){7}([0-9]|[a-f]|[A-F]){4}$/"; |
|
34
|
|
|
|
|
35
|
7 |
|
$iptoip6 = $this->input2ip6($ip); |
|
36
|
|
|
|
|
37
|
7 |
|
if (preg_match($ipv6, $iptoip6)) { |
|
38
|
2 |
|
return true; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
7 |
|
return false; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
16 |
|
public function padIP($mymy) : array |
|
45
|
|
|
{ |
|
46
|
16 |
|
$newip6 = []; |
|
47
|
16 |
|
$mycount = count($mymy); |
|
48
|
16 |
|
$missing = 8 - $mycount; // IPv6 has eight 16bit blocks |
|
49
|
16 |
|
for ($i=0; $i < $mycount; $i++) { |
|
50
|
16 |
|
array_push($newip6, str_pad($mymy[$i], 4, "0", STR_PAD_LEFT)); |
|
51
|
16 |
|
if ($mymy[$i] === "") { |
|
52
|
9 |
|
for ($j=0; $j < $missing; $j++) { |
|
53
|
9 |
|
array_push($newip6, str_pad($mymy[$i], 4, "0", STR_PAD_LEFT)); |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
16 |
|
return $newip6; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
18 |
|
public function corrected($ipinput) : array |
|
61
|
|
|
{ |
|
62
|
18 |
|
$newip6 = []; |
|
63
|
18 |
|
if ($ipinput) { |
|
64
|
16 |
|
$mymy = explode(":", $ipinput); |
|
65
|
16 |
|
if ($mymy[0] === "") { |
|
66
|
5 |
|
array_shift($mymy); |
|
67
|
15 |
|
} elseif ($mymy[count($mymy) -1] === "") { |
|
68
|
3 |
|
array_pop($mymy); |
|
69
|
|
|
} |
|
70
|
16 |
|
$newip6 = $this->padIP($mymy); |
|
71
|
|
|
} |
|
72
|
18 |
|
return $newip6; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
7 |
|
private function input2ip6($ip) : string |
|
76
|
|
|
{ |
|
77
|
7 |
|
$newip6 = $this->corrected($ip); |
|
78
|
7 |
|
$newip6str = implode(":", $newip6); |
|
79
|
7 |
|
return $newip6str; |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|