1 | <?php |
||
2 | |||
3 | namespace Bavix\IP; |
||
4 | |||
5 | class Util |
||
6 | { |
||
7 | |||
8 | /** |
||
9 | * @var int |
||
10 | */ |
||
11 | public const IPv4_INT_MAX = 4294967295; |
||
12 | |||
13 | /** |
||
14 | * @param string $ip |
||
15 | * |
||
16 | * @return bool |
||
17 | */ |
||
18 | public static function isIPv6(string $ip): bool |
||
19 | { |
||
20 | return (bool)\inet_ntop($ip); |
||
21 | } |
||
22 | |||
23 | /** |
||
24 | * @param string $ip |
||
25 | * |
||
26 | * @return bool |
||
27 | */ |
||
28 | public static function isIPv4(string $ip): bool |
||
29 | { |
||
30 | return (bool)\ip2long($ip); |
||
31 | } |
||
32 | |||
33 | /** |
||
34 | * @param string $ip |
||
35 | * @return string |
||
36 | */ |
||
37 | public static function ip2long(string $ip): string |
||
38 | { |
||
39 | return \gmp_import(\inet_pton($ip)); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
40 | } |
||
41 | |||
42 | /** |
||
43 | * @param string $long |
||
44 | * @param bool $forceIPv6 |
||
45 | * @return string |
||
46 | */ |
||
47 | public static function long2ip(string $long, bool $forceIPv6 = false): string |
||
48 | { |
||
49 | /** |
||
50 | * @var \GMP $long |
||
51 | */ |
||
52 | if ($forceIPv6 || \gmp_cmp($long, static::IPv4_INT_MAX) > 0) { |
||
53 | return (string)\inet_ntop( |
||
54 | \str_pad( |
||
55 | \gmp_export($long), |
||
56 | 16, |
||
57 | "\0", |
||
58 | \STR_PAD_LEFT |
||
59 | ) |
||
60 | ); |
||
61 | } |
||
62 | |||
63 | return \long2ip($long); |
||
64 | } |
||
65 | |||
66 | } |
||
67 |