File size: 1,640 Bytes
e4f4821 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<?php
namespace JsonRPC\Validator;
use JsonRPC\Exception\AccessDeniedException;
/**
* Class HostValidator
*
* @package JsonRPC\Validator
* @author Frederic Guillot
*/
class HostValidator
{
/**
* Validate
*
* @static
* @access public
* @param array $hosts
* @param string $remoteAddress
* @throws AccessDeniedException
*/
public static function validate(array $hosts, $remoteAddress)
{
if (!empty($hosts)) {
foreach ($hosts as $host) {
if (self::ipMatch($remoteAddress, $host)) {
return;
}
}
throw new AccessDeniedException('Access Forbidden');
}
}
/**
* Validate remoteAddress match host
* @param $remoteAddress
* @param $host
* @return bool
*/
public static function ipMatch($remoteAddress, $host)
{
$host = trim($host);
if (strpos($host, '/') !== false) {
list($network, $mask) = explode('/', $host);
if (self::netMatch($remoteAddress, $network, $mask)) {
return true;
}
}
if ($host === $remoteAddress) {
return true;
}
return false;
}
/**
* validate the ipAddress in network
* 192.168.1.1/24
* @param $clientIp
* @param $networkIp
* @param $mask
*
* @return bool
*/
public static function netMatch($clientIp, $networkIp, $mask)
{
$mask1 = 32 - $mask;
return ((ip2long($clientIp) >> $mask1) == (ip2long($networkIp) >> $mask1));
}
}
|