3 * @Author "Ashar Voultoiz" <hashar@altern.org>
4 * @License GPL v2 or later
7 // Some regex definition to "play" with IP address and IP address blocks
9 // An IP is made of 4 bytes from x00 to xFF which is d0 to d255
10 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])');
11 define( 'RE_IP_ADD' , RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
);
12 // An IPv4 block is an IP address and a prefix (d1 to d32)
13 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)');
14 define( 'RE_IP_BLOCK', RE_IP_ADD
. '\/' . RE_IP_PREFIX
);
15 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
16 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
17 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
18 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP
. '(?:ffff:)?' );
19 // An IPv6 block is an IP address and a prefix (d1 to d128)
20 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
21 // An IPv6 IP is made up of 8 octets. However abbreviations like "::" can be used. This is lax!
22 define( 'RE_IPV6_ADD', '(:(:' . RE_IPV6_WORD
. '){1,7}|' . RE_IPV6_WORD
. '(:{1,2}' . RE_IPV6_WORD
. '|::$){1,7})' );
23 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD
. '\/' . RE_IPV6_PREFIX
);
24 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
25 define( 'IP_ADDRESS_STRING', RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)|' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)');
28 * A collection of public static functions to play with IP address
33 * Given a string, determine if it as valid IP
34 * Unlike isValid(), this looks for networks too
35 * @param $ip IP address.
38 public static function isIPAddress( $ip ) {
39 if ( !$ip ) return false;
40 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
41 return preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip) && ( substr_count($ip, '::') < 2 );
44 public static function isIPv6( $ip ) {
45 if ( !$ip ) return false;
46 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
47 return preg_match( '/^' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)$/', $ip) && ( substr_count($ip, '::') < 2);
50 public static function isIPv4( $ip ) {
51 if ( !$ip ) return false;
52 return preg_match( '/^' . RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)$/', $ip);
56 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
57 * See http://www.answers.com/topic/ipv4-compatible-address
58 * IPs with the first 92 bits as zeros are reserved from IPv6
59 * @param $ip quad-dotted IP address.
62 public static function IPv4toIPv6( $ip ) {
63 if ( !$ip ) return null;
64 // Convert only if needed
65 if ( self
::isIPv6( $ip ) ) return $ip;
67 if ( strpos( $ip, '/' ) !== false ) {
68 $parts = explode( '/', $ip, 2 );
69 if ( count( $parts ) != 2 ) {
72 $network = self
::toUnsigned( $parts[0] );
73 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
74 $bits = $parts[1] +
96;
75 return self
::toOctet( $network ) . "/$bits";
80 return self
::toOctet( self
::toUnsigned( $ip ) );
84 * Given an IPv6 address in octet notation, returns an unsigned integer.
85 * @param $ip octet ipv6 IP address.
88 public static function toUnsigned6( $ip ) {
89 if ( !$ip ) return null;
90 $ip = explode(':', self
::sanitizeIP( $ip ) );
93 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT
);
95 $r_ip = wfBaseConvert( $r_ip, 16, 10 );
100 * Given an IPv6 address in octet notation, returns the expanded octet.
101 * IPv4 IPs will be trimmed, thats it...
102 * @param $ip octet ipv6 IP address.
105 public static function sanitizeIP( $ip ) {
106 if ( !$ip ) return null;
107 // Trim and return IPv4 addresses
108 if ( self
::isIPv4($ip) ) return trim($ip);
109 // Only IPv6 addresses can be expanded
110 if ( !self
::isIPv6($ip) ) return $ip;
111 // Remove any whitespaces, convert to upper case
112 $ip = strtoupper( trim($ip) );
113 // Expand zero abbreviations
114 if ( strpos( $ip, '::' ) !== false ) {
115 $ip = str_replace('::', str_repeat(':0', 8 - substr_count($ip, ':')) . ':', $ip);
117 // For IPs that start with "::", correct the final IP so that it starts with '0' and not ':'
118 if ( $ip[0] == ':' ) $ip = "0$ip";
119 // Remove leading zereos from each bloc as needed
120 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip );
125 * Given an unsigned integer, returns an IPv6 address in octet notation
126 * @param $ip integer IP address.
129 public static function toOctet( $ip_int ) {
130 // Convert to padded uppercase hex
131 $ip_hex = wfBaseConvert($ip_int, 10, 16, 32, false);
132 // Seperate into 8 octets
133 $ip_oct = substr( $ip_hex, 0, 4 );
134 for ($n=1; $n < 8; $n++
) {
135 $ip_oct .= ':' . substr($ip_hex, 4*$n, 4);
138 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip_oct );
143 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
144 * @return array(string, int)
146 public static function parseCIDR6( $range ) {
148 $parts = explode( '/', IP
::sanitizeIP( $range ), 2 );
149 if ( count( $parts ) != 2 ) {
150 return array( false, false );
152 $network = self
::toUnsigned6( $parts[0] );
153 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
158 # Native 32 bit functions WONT work here!!!
159 # Convert to a padded binary number
160 $network = wfBaseConvert( $network, 10, 2, 128 );
161 # Truncate the last (128-$bits) bits and replace them with zeros
162 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
163 # Convert back to an integer
164 $network = wfBaseConvert( $network, 2, 10 );
170 return array( $network, $bits );
174 * Given a string range in a number of formats, return the start and end of
175 * the range in hexadecimal. For IPv6.
178 * 2001:0db8:85a3::7344/96 CIDR
179 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
180 * 2001:0db8:85a3::7344/96 Single IP
181 * @return array(string, int)
183 public static function parseRange6( $range ) {
185 $range = IP
::sanitizeIP( $range );
186 if ( strpos( $range, '/' ) !== false ) {
188 list( $network, $bits ) = self
::parseCIDR6( $range );
189 if ( $network === false ) {
190 $start = $end = false;
192 $start = wfBaseConvert( $network, 10, 16, 32, false );
193 # Turn network to binary (again)
194 $end = wfBaseConvert( $network, 10, 2, 128 );
195 # Truncate the last (128-$bits) bits and replace them with ones
196 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT
);
198 $end = wfBaseConvert( $end, 2, 16, 32, false );
199 # see toHex() comment
200 $start = "v6-$start"; $end = "v6-$end";
202 } elseif ( strpos( $range, '-' ) !== false ) {
204 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
205 $start = self
::toUnsigned6( $start ); $end = self
::toUnsigned6( $end );
206 if ( $start > $end ) {
207 $start = $end = false;
209 $start = wfBaseConvert( $start, 10, 16, 32, false );
210 $end = wfBaseConvert( $end, 10, 16, 32, false );
212 # see toHex() comment
213 $start = "v6-$start"; $end = "v6-$end";
216 $start = $end = self
::toHex( $range );
218 if ( $start === false ||
$end === false ) {
219 return array( false, false );
221 return array( $start, $end );
226 * Validate an IP address.
227 * @return boolean True if it is valid.
229 public static function isValid( $ip ) {
230 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip) );
234 * Validate an IP Block.
235 * @return boolean True if it is valid.
237 public static function isValidBlock( $ipblock ) {
238 return ( count(self
::toArray($ipblock)) == 1 +
5 );
242 * Determine if an IP address really is an IP address, and if it is public,
243 * i.e. not RFC 1918 or similar
244 * Comes from ProxyTools.php
246 public static function isPublic( $ip ) {
247 $n = self
::toUnsigned( $ip );
252 // ip2long accepts incomplete addresses, as well as some addresses
253 // followed by garbage characters. Check that it's really valid.
254 if( $ip != long2ip( $n ) ) {
258 static $privateRanges = false;
259 if ( !$privateRanges ) {
260 $privateRanges = array(
261 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
262 array( '172.16.0.0', '172.31.255.255' ), # "
263 array( '192.168.0.0', '192.168.255.255' ), # "
264 array( '0.0.0.0', '0.255.255.255' ), # this network
265 array( '127.0.0.0', '127.255.255.255' ), # loopback
269 foreach ( $privateRanges as $r ) {
270 $start = self
::toUnsigned( $r[0] );
271 $end = self
::toUnsigned( $r[1] );
272 if ( $n >= $start && $n <= $end ) {
280 * Split out an IP block as an array of 4 bytes and a mask,
281 * return false if it can't be determined
283 * @param $ip string A quad dotted/octet IP address
286 public static function toArray( $ipblock ) {
288 if( preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:'.RE_IP_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
290 } else if ( preg_match( '/^' . RE_IPV6_ADD
. '(?:\/(?:'.RE_IPV6_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
298 * Return a zero-padded hexadecimal representation of an IP address.
300 * Hexadecimal addresses are used because they can easily be extended to
301 * IPv6 support. To separate the ranges, the return value from this
302 * function for an IPv6 address will be prefixed with "v6-", a non-
303 * hexadecimal string which sorts after the IPv4 addresses.
305 * @param $ip Quad dotted/octet IP address.
306 * @return hexidecimal
308 public static function toHex( $ip ) {
309 $n = self
::toUnsigned( $ip );
310 if ( $n !== false ) {
311 $n = ( self
::isIPv6($ip) ) ?
"v6-" . wfBaseConvert( $n, 10, 16, 32, false ) : wfBaseConvert( $n, 10, 16, 8, false );
317 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
318 * Like ip2long() except that it actually works and has a consistent error return value.
319 * Comes from ProxyTools.php
320 * @param $ip Quad dotted IP address.
323 public static function toUnsigned( $ip ) {
324 // Use IPv6 functions if needed
325 if ( self
::isIPv6( $ip ) ) {
326 return self
::toUnsigned6( $ip );
328 if ( $ip == '255.255.255.255' ) {
332 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
343 * Convert a dotted-quad IP to a signed integer
344 * Returns false on failure
346 public static function toSigned( $ip ) {
347 if ( $ip == '255.255.255.255' ) {
359 * Convert a network specification in CIDR notation to an integer network and a number of bits
360 * @return array(string, int)
362 public static function parseCIDR( $range ) {
363 $parts = explode( '/', $range, 2 );
364 if ( count( $parts ) != 2 ) {
365 return array( false, false );
367 $network = self
::toSigned( $parts[0] );
368 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
373 $network &= ~
((1 << (32 - $bits)) - 1);
375 # Convert to unsigned
376 if ( $network < 0 ) {
377 $network +
= pow( 2, 32 );
383 return array( $network, $bits );
387 * Given a string range in a number of formats, return the start and end of
388 * the range in hexadecimal.
392 * 1.2.3.4 - 1.2.3.5 Explicit range
395 * 2001:0db8:85a3::7344/96 CIDR
396 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
397 * 2001:0db8:85a3::7344 Single IP
398 * @return array(string, int)
400 public static function parseRange( $range ) {
401 // Use IPv6 functions if needed
402 if ( self
::isIPv6( $range ) ) {
403 return self
::parseRange6( $range );
405 if ( strpos( $range, '/' ) !== false ) {
407 list( $network, $bits ) = self
::parseCIDR( $range );
408 if ( $network === false ) {
409 $start = $end = false;
411 $start = sprintf( '%08X', $network );
412 $end = sprintf( '%08X', $network +
pow( 2, (32 - $bits) ) - 1 );
414 } elseif ( strpos( $range, '-' ) !== false ) {
416 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
417 $start = self
::toUnsigned( $start ); $end = self
::toUnsigned( $end );
418 if ( $start > $end ) {
419 $start = $end = false;
421 $start = sprintf( '%08X', $start );
422 $end = sprintf( '%08X', $end );
426 $start = $end = self
::toHex( $range );
428 if ( $start === false ||
$end === false ) {
429 return array( false, false );
431 return array( $start, $end );
436 * Determine if a given IPv4/IPv6 address is in a given CIDR network
437 * @param $addr The address to check against the given range.
438 * @param $range The range to check the given address against.
439 * @return bool Whether or not the given address is in the given range.
441 public static function isInRange( $addr, $range ) {
442 // Convert to IPv6 if needed
443 $unsignedIP = self
::toHex( $addr );
444 list( $start, $end ) = self
::parseRange( $range );
445 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
449 * Convert some unusual representations of IPv4 addresses to their
450 * canonical dotted quad representation.
452 * This currently only checks a few IPV4-to-IPv6 related cases. More
453 * unusual representations may be added later.
455 * @param $addr something that might be an IP address
456 * @return valid dotted quad IPv4 address or null
458 public static function canonicalize( $addr ) {
459 if ( self
::isValid( $addr ) )
462 // IPv6 loopback address
464 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) )
467 // IPv4-mapped and IPv4-compatible IPv6 addresses
468 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) )
470 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
471 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
473 return null; // give up