IpCheck   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 67
rs 10
c 0
b 0
f 0
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValidIpAddress() 0 10 3
B addressType() 0 31 7
1
<?php
2
3
namespace XoopsModules\Newbb;
4
5
//adopted from poweradmin (https://github.com/poweradmin)
6
7
/**
8
 * Class IpCheck
9
 */
10
class IpCheck
11
{
12
    /** @var string */
13
    private $ipin;
14
15
    /** @var string */
16
    private $ipout;
17
18
    /** @var int */
19
    private $ipver;
20
21
    // Return IP type.  4 for IPv4, 6 for IPv6, 0 for bad IP.
22
23
    /**
24
     * @param $ipValue
25
     */
26
    public function addressType($ipValue)
27
    {
28
        $this->ipin  = $ipValue;
29
        $this->ipver = 0;
30
31
        // IPv4 addresses are easy-peasy
32
        if (\filter_var($this->ipin, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
33
            $this->ipver = 4;
34
            $this->ipout = $this->ipin;
35
        }
36
37
        // IPv6 is at least a little more complex.
38
        if (\filter_var($this->ipin, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
39
            // Look for embedded IPv4 in an embedded IPv6 address, where FFFF is appended.
40
            if (0 === \strncmp($this->ipin, '::FFFF:', 7)) {
41
                $ipv4addr = mb_substr($this->ipin, 7);
42
                if (\filter_var($ipv4addr, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
43
                    $this->ipver = 4;
44
                    $this->ipout = $ipv4addr;
45
                }
46
                // Look for an IPv4 address embedded as ::x.x.x.x
47
            } elseif (0 === mb_strpos($this->ipin, '::')) {
48
                $ipv4addr = mb_substr($this->ipin, 2);
49
                if (\filter_var($ipv4addr, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
50
                    $this->ipver = 4;
51
                    $this->ipout = $ipv4addr;
52
                }
53
                // Otherwise, assume this an IPv6 address.
54
            } else {
55
                $this->ipver = 6;
56
                $this->ipout = $this->ipin;
57
            }
58
        }
59
    }
60
61
    /** Check whether the given address is an IP address
62
     *
63
     * @param string $ip Given IP address
64
     *
65
     * @return string A if IPv4, AAAA if IPv6 or 0 if invalid
66
     */
67
    public function isValidIpAddress($ip)
68
    {
69
        $value = 0;
70
        if (\filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
71
            $value = 'A';
72
        } elseif (\filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
73
            $value = 'AAAA';
74
        }
75
76
        return $value;
77
    }
78
}
79