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
|
18 |
|
public function corrected($ipinput): array |
45
|
|
|
{ |
46
|
18 |
|
$newip6 = []; |
47
|
18 |
|
if ($ipinput) { |
48
|
16 |
|
$mymy = explode(":", $ipinput); |
49
|
16 |
|
if ($mymy[0] === "") { |
50
|
5 |
|
array_shift($mymy); |
51
|
15 |
|
} elseif ($mymy[count($mymy) -1] === "") { |
52
|
3 |
|
array_pop($mymy); |
53
|
|
|
} |
54
|
16 |
|
$mycount = count($mymy); |
55
|
16 |
|
$missing = 8 - $mycount; // IPv6 has eight 16bit blocks |
56
|
16 |
|
for ($i=0; $i < $mycount; $i++) { |
57
|
16 |
|
array_push($newip6, str_pad($mymy[$i], 4, "0", STR_PAD_LEFT)); |
58
|
16 |
|
if ($mymy[$i] === "") { |
59
|
9 |
|
for ($j=0; $j < $missing; $j++) { |
60
|
9 |
|
array_push($newip6, str_pad($mymy[$i], 4, "0", STR_PAD_LEFT)); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
18 |
|
return $newip6; |
66
|
|
|
} |
67
|
|
|
|
68
|
7 |
|
private function input2ip6($ip) : string |
69
|
|
|
{ |
70
|
7 |
|
$newip6 = $this->corrected($ip); |
71
|
|
|
// $newip6 = []; |
72
|
|
|
// if ($ip) { |
73
|
|
|
// $mymy = explode(":", $ip); |
74
|
|
|
// if ($mymy[0] === "") { |
75
|
|
|
// array_shift($mymy); |
76
|
|
|
// } elseif ($mymy[count($mymy) -1] === "") { |
77
|
|
|
// array_pop($mymy); |
78
|
|
|
// } |
79
|
|
|
// $mycount = count($mymy); |
80
|
|
|
// $missing = 8 - $mycount; // IPv6 has eight 16bit blocks |
81
|
|
|
// for ($i=0; $i < $mycount; $i++) { |
82
|
|
|
// array_push($newip6, str_pad($mymy[$i], 4, "0", STR_PAD_LEFT)); |
83
|
|
|
// if ($mymy[$i] === "") { |
84
|
|
|
// for ($j=0; $j < $missing; $j++) { |
85
|
|
|
// array_push($newip6, str_pad($mymy[$i], 4, "0", STR_PAD_LEFT)); |
86
|
|
|
// } |
87
|
|
|
// } |
88
|
|
|
// } |
89
|
|
|
// } |
90
|
7 |
|
$newip6str = implode(":", $newip6); |
91
|
7 |
|
return $newip6str; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|