public static function IPTools::validateIP in Restrict Login or Role Access by IP Address 8.4
Given a string, validate that it is valid IP address.
Overrides IPToolsInterface::validateIP
2 calls to IPTools::validateIP()
- UnitTest::testIpFailValidation in tests/
src/ Unit/ UnitTest.php - @dataProvider invalidIpProvider @expectedException \Drupal\restrict_by_ip\Exception\InvalidIPException
- UnitTest::testIpPassValidation in tests/
src/ Unit/ UnitTest.php - @dataProvider validIpProvider
File
- src/
IPTools.php, line 39
Class
- IPTools
- Class IPTools.
Namespace
Drupal\restrict_by_ipCode
public static function validateIP($ip) {
// Separate in to address and CIDR mask.
$cidr = explode("/", $ip);
// Check address and cidr mask entered.
if (count($cidr) !== 2) {
throw new InvalidIPException('IP address must be in CIDR notation.');
}
$ipaddr = explode(".", $cidr[0]);
// Check four octets entered.
if (count($ipaddr) != 4) {
throw new InvalidIPException('IP address must have four octets.');
}
// Check each octet is valid - numeric and 0 < value < 255.
for ($i = 0; $i < count($ipaddr); $i++) {
if (!is_numeric($ipaddr[$i]) || $ipaddr[$i] < 0 || $ipaddr[$i] > 255) {
throw new InvalidIPException('Octet must be between 0 and 255.');
}
}
// Check cidr mask value - numeric and 0 < value < 33.
if (!is_numeric($cidr[1]) || $cidr[1] < 1 || $cidr[1] > 32) {
throw new InvalidIPException('Routing prefix must be between 0 and 32.');
}
// Check the validity of the network address in the given CIDR block,
// by ensuring that the network address part is valid within the
// CIDR block itself. If it's not, the notation is invalid.
try {
self::validateCIDR($cidr[0], $ip);
} catch (IPOutOfRangeException $e) {
throw new InvalidIPException('IP address and routing prefix are not a valid combination.');
}
}