ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
Net.php
Go to the documentation of this file.
1<?php
2namespace SimpleSAML\Utils;
3
9class Net
10{
11
26 public static function ipCIDRcheck($cidr, $ip = null)
27 {
28 if ($ip === null) {
29 $ip = $_SERVER['REMOTE_ADDR'];
30 }
31 if (strpos($cidr, '/') === false) {
32 return false;
33 }
34
35 list ($net, $mask) = explode('/', $cidr);
36 $mask = intval($mask);
37
38 $ip_ip = array();
39 $ip_net = array();
40 if (strstr($ip, ':') || strstr($net, ':')) {
41 // Validate IPv6 with inet_pton, convert to hex with bin2hex
42 // then store as a long with hexdec
43
44 $ip_pack = @inet_pton($ip);
45 $net_pack = @inet_pton($net);
46
47 if ($ip_pack === false || $net_pack === false) {
48 // not valid IPv6 address (warning silenced)
49 return false;
50 }
51
52 $ip_ip = str_split(bin2hex($ip_pack), 8);
53 foreach ($ip_ip as &$value) {
54 $value = hexdec($value);
55 }
56
57 $ip_net = str_split(bin2hex($net_pack), 8);
58 foreach ($ip_net as &$value) {
59 $value = hexdec($value);
60 }
61 } else {
62 $ip_ip[0] = ip2long($ip);
63 $ip_net[0] = ip2long($net);
64 }
65
66 for ($i = 0; $mask > 0 && $i < sizeof($ip_ip); $i++) {
67 if ($mask > 32) {
68 $iteration_mask = 32;
69 } else {
70 $iteration_mask = $mask;
71 }
72 $mask -= 32;
73
74 $ip_mask = ~((1 << (32 - $iteration_mask)) - 1);
75
76 $ip_net_mask = $ip_net[$i] & $ip_mask;
77 $ip_ip_mask = $ip_ip[$i] & $ip_mask;
78
79 if ($ip_ip_mask != $ip_net_mask) {
80 return false;
81 }
82 }
83 return true;
84 }
85}
An exception for terminatinating execution or to throw for unit testing.
static ipCIDRcheck($cidr, $ip=null)
Check whether an IP address is part of a CIDR.
Definition: Net.php:26
$i
Definition: disco.tpl.php:19
$mask
Definition: example_042.php:90
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']