1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Symfony\Component\HttpFoundation;
13:
14: 15: 16: 17: 18:
19: class IpUtils
20: {
21: 22: 23:
24: private function __construct() {}
25:
26: 27: 28: 29: 30: 31: 32: 33:
34: public static function checkIp($requestIp, $ip)
35: {
36: if (false !== strpos($requestIp, ':')) {
37: return self::checkIp6($requestIp, $ip);
38: }
39:
40: return self::checkIp4($requestIp, $ip);
41: }
42:
43: 44: 45: 46: 47: 48: 49: 50:
51: public static function checkIp4($requestIp, $ip)
52: {
53: if (false !== strpos($ip, '/')) {
54: list($address, $netmask) = explode('/', $ip, 2);
55:
56: if ($netmask < 1 || $netmask > 32) {
57: return false;
58: }
59: } else {
60: $address = $ip;
61: $netmask = 32;
62: }
63:
64: return 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask);
65: }
66:
67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79:
80: public static function checkIp6($requestIp, $ip)
81: {
82: if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1'))) {
83: throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
84: }
85:
86: if (false !== strpos($ip, '/')) {
87: list($address, $netmask) = explode('/', $ip, 2);
88:
89: if ($netmask < 1 || $netmask > 128) {
90: return false;
91: }
92: } else {
93: $address = $ip;
94: $netmask = 128;
95: }
96:
97: $bytesAddr = unpack("n*", inet_pton($address));
98: $bytesTest = unpack("n*", inet_pton($requestIp));
99:
100: for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; $i++) {
101: $left = $netmask - 16 * ($i-1);
102: $left = ($left <= 16) ? $left : 16;
103: $mask = ~(0xffff >> $left) & 0xffff;
104: if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
105: return false;
106: }
107: }
108:
109: return true;
110: }
111: }
112: