3 * Functions and constants to play with IP addresses and ranges
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Ashar Voultoiz <hashar at free dot fr>
24 // Some regex definition to "play" with IP address and IP address blocks
26 // An IP is made of 4 bytes from x00 to xFF which is d0 to d255
27 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
28 define( 'RE_IP_ADD' , RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
);
29 // An IPv4 block is an IP address and a prefix (d1 to d32)
30 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)' );
31 define( 'RE_IP_BLOCK', RE_IP_ADD
. '\/' . RE_IP_PREFIX
);
32 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
33 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
34 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
35 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP
. '(?:ffff:)?' );
36 // An IPv6 block is an IP address and a prefix (d1 to d128)
37 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
38 // An IPv6 IP is made up of 8 octets. However abbreviations like "::" can be used.
39 // This is lax! The number of colon groups is checked (1 to 7) but
40 // the number of double colons is not validated (must be 0 to 1).
41 define( 'RE_IPV6_ADD',
43 ':(:' . RE_IPV6_WORD
. '){1,7}' . // starts with "::"
45 RE_IPV6_WORD
. '(:{1,2}' . RE_IPV6_WORD
. '){0,6}::' . // ends with "::"
47 RE_IPV6_WORD
. '(:{1,2}' . RE_IPV6_WORD
. '){1,7}' . // neither of the above
50 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD
. '\/' . RE_IPV6_PREFIX
);
51 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
52 define( 'IP_ADDRESS_STRING',
54 RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)' . // IPv4
56 RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)' . // IPv6
61 * A collection of public static functions to play with IP address
66 * Given a string, determine if it as valid IP.
67 * Note: Unlike isValid(), this looks for networks too.
68 * @param $ip string possible IP address
71 public static function isIPAddress( $ip ) {
75 if ( is_array( $ip ) ) {
76 throw new MWException( 'invalid value passed to ' . __METHOD__
);
78 return preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip )
79 && ( substr_count( $ip, '::' ) <= 1 ); // IPv6 IPs with 2+ "::" are ambiguous
83 * Given a string, determine if it as valid IP in IPv6 only.
84 * Note: Unlike isValid(), this looks for networks too.
85 * @param $ip string possible IP address
88 public static function isIPv6( $ip ) {
92 if ( is_array( $ip ) ) {
93 throw new MWException( 'invalid value passed to ' . __METHOD__
);
95 return preg_match( '/^' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)$/', $ip )
96 && ( substr_count( $ip, '::' ) <= 1 ); // IPv6 IPs with 2+ "::" are ambiguous
100 * Given a string, determine if it as valid IP in IPv4 only.
101 * Note: Unlike isValid(), this looks for networks too.
102 * @param $ip string possible IP address
105 public static function isIPv4( $ip ) {
109 return preg_match( '/^' . RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)$/', $ip );
113 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
114 * See http://www.answers.com/topic/ipv4-compatible-address
115 * IPs with the first 92 bits as zeros are reserved from IPv6
116 * @param $ip quad-dotted IP address.
119 public static function IPv4toIPv6( $ip ) {
123 // Convert only if needed
124 if ( self
::isIPv6( $ip ) ) {
128 if ( strpos( $ip, '/' ) !== false ) {
129 $parts = explode( '/', $ip, 2 );
130 if ( count( $parts ) != 2 ) {
133 list( $network, $bits ) = $parts;
134 $network = self
::toUnsigned( $network );
135 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
137 return self
::toOctet( $network ) . "/$bits";
142 return self
::toOctet( self
::toUnsigned( $ip ) );
146 * Given an IPv6 address in octet notation, returns an unsigned integer.
147 * @param $ip octet ipv6 IP address.
150 public static function toUnsigned6( $ip ) {
154 $ip = explode( ':', self
::sanitizeIP( $ip ) );
156 foreach ( $ip as $v ) {
157 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT
);
159 $r_ip = wfBaseConvert( $r_ip, 16, 10 );
164 * Given an IPv6 address in octet notation, returns the expanded octet.
165 * IPv4 IPs will be trimmed, thats it...
166 * @param $ip octet ipv6 IP address.
169 public static function sanitizeIP( $ip ) {
174 // Trim and return IPv4 addresses
175 if ( self
::isIPv4( $ip ) ) {
178 // Only IPv6 addresses can be expanded
179 if ( !self
::isIPv6( $ip ) ) {
182 // Remove any whitespaces, convert to upper case
183 $ip = strtoupper( $ip );
184 // Expand zero abbreviations
185 $abbrevPos = strpos( $ip, '::' );
186 if ( $abbrevPos !== false ) {
187 // If the '::' is at the beginning...
188 if( $abbrevPos == 0 ) {
191 $pad = 9; // 7+2 (due to '::')
192 // If the '::' is at the end...
193 } elseif( $abbrevPos == ( strlen( $ip ) - 2 ) ) {
196 $pad = 9; // 7+2 (due to '::')
197 // If the '::' is at the end...
201 $pad = 8; // 6+2 (due to '::')
203 $ip = str_replace( '::',
204 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
208 // Remove leading zereos from each bloc as needed
209 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip );
214 * Given an unsigned integer, returns an IPv6 address in octet notation
215 * @param $ip_int integer IP address.
218 public static function toOctet( $ip_int ) {
219 // Convert to padded uppercase hex
220 $ip_hex = wfBaseConvert( $ip_int, 10, 16, 32, false );
221 // Separate into 8 octets
222 $ip_oct = substr( $ip_hex, 0, 4 );
223 for ( $n = 1; $n < 8; $n++
) {
224 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
227 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip_oct );
232 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
233 * @param $hex string number, with "v6-" prefix if it is IPv6
234 * @return string quad-dotted (IPv4) or octet notation (IPv6)
236 public static function formatHex( $hex ) {
237 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
238 return self
::hexToOctet( substr( $hex, 3 ) );
240 return self
::hexToQuad( $hex );
245 * Converts a hexadecimal number to an IPv6 address in octet notation
246 * @param $ip_hex string hex IP
247 * @return string (of format a:b:c:d:e:f:g:h)
249 public static function hexToOctet( $ip_hex ) {
250 // Convert to padded uppercase hex
251 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0' );
252 // Separate into 8 octets
253 $ip_oct = substr( $ip_hex, 0, 4 );
254 for ( $n = 1; $n < 8; $n++
) {
255 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
258 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip_oct );
263 * Converts a hexadecimal number to an IPv4 address in quad-dotted notation
264 * @param $ip string Hex IP
265 * @return string (of format a.b.c.d)
267 public static function hexToQuad( $ip ) {
269 for ( $i = 0; $i < 4; $i++
) {
273 $s .= base_convert( substr( $ip, $i * 2, 2 ), 16, 10 );
279 * Convert a network specification in IPv6 CIDR notation to an
280 * integer network and a number of bits
281 * @return array(string, int)
283 public static function parseCIDR6( $range ) {
284 # Explode into <expanded IP,range>
285 $parts = explode( '/', IP
::sanitizeIP( $range ), 2 );
286 if ( count( $parts ) != 2 ) {
287 return array( false, false );
289 list( $network, $bits ) = $parts;
290 $network = self
::toUnsigned6( $network );
291 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
295 # Native 32 bit functions WONT work here!!!
296 # Convert to a padded binary number
297 $network = wfBaseConvert( $network, 10, 2, 128 );
298 # Truncate the last (128-$bits) bits and replace them with zeros
299 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
300 # Convert back to an integer
301 $network = wfBaseConvert( $network, 2, 10 );
307 return array( $network, (int)$bits );
311 * Given a string range in a number of formats, return the start and end of
312 * the range in hexadecimal. For IPv6.
315 * 2001:0db8:85a3::7344/96 CIDR
316 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
317 * 2001:0db8:85a3::7344/96 Single IP
318 * @return array(string, int)
320 public static function parseRange6( $range ) {
322 $range = IP
::sanitizeIP( $range );
324 if ( strpos( $range, '/' ) !== false ) {
325 list( $network, $bits ) = self
::parseCIDR6( $range );
326 if ( $network === false ) {
327 $start = $end = false;
329 $start = wfBaseConvert( $network, 10, 16, 32, false );
330 # Turn network to binary (again)
331 $end = wfBaseConvert( $network, 10, 2, 128 );
332 # Truncate the last (128-$bits) bits and replace them with ones
333 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT
);
335 $end = wfBaseConvert( $end, 2, 16, 32, false );
336 # see toHex() comment
337 $start = "v6-$start";
340 // Explicit range notation...
341 } elseif ( strpos( $range, '-' ) !== false ) {
342 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
343 $start = self
::toUnsigned6( $start );
344 $end = self
::toUnsigned6( $end );
345 if ( $start > $end ) {
346 $start = $end = false;
348 $start = wfBaseConvert( $start, 10, 16, 32, false );
349 $end = wfBaseConvert( $end, 10, 16, 32, false );
351 # see toHex() comment
352 $start = "v6-$start";
356 $start = $end = self
::toHex( $range );
358 if ( $start === false ||
$end === false ) {
359 return array( false, false );
361 return array( $start, $end );
366 * Validate an IP address.
367 * @return boolean True if it is valid.
369 public static function isValid( $ip ) {
370 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip ) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip ) );
374 * Validate an IP Block.
375 * @return boolean True if it is valid.
377 public static function isValidBlock( $ipblock ) {
378 return ( count( self
::toArray( $ipblock ) ) == 1 +
5 );
382 * Determine if an IP address really is an IP address, and if it is public,
383 * i.e. not RFC 1918 or similar
384 * Comes from ProxyTools.php
386 public static function isPublic( $ip ) {
387 $n = self
::toUnsigned( $ip );
392 // ip2long accepts incomplete addresses, as well as some addresses
393 // followed by garbage characters. Check that it's really valid.
394 if( $ip != long2ip( $n ) ) {
398 static $privateRanges = false;
399 if ( !$privateRanges ) {
400 $privateRanges = array(
401 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
402 array( '172.16.0.0', '172.31.255.255' ), # "
403 array( '192.168.0.0', '192.168.255.255' ), # "
404 array( '0.0.0.0', '0.255.255.255' ), # this network
405 array( '127.0.0.0', '127.255.255.255' ), # loopback
409 foreach ( $privateRanges as $r ) {
410 $start = self
::toUnsigned( $r[0] );
411 $end = self
::toUnsigned( $r[1] );
412 if ( $n >= $start && $n <= $end ) {
420 * Split out an IP block as an array of 4 bytes and a mask,
421 * return false if it can't be determined
423 * @param $ipblock string A quad dotted/octet IP address
426 public static function toArray( $ipblock ) {
428 if( preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:' . RE_IP_PREFIX
. '))?' . '$/', $ipblock, $matches ) ) {
430 } elseif ( preg_match( '/^' . RE_IPV6_ADD
. '(?:\/(?:' . RE_IPV6_PREFIX
. '))?' . '$/', $ipblock, $matches ) ) {
438 * Return a zero-padded hexadecimal representation of an IP address.
440 * Hexadecimal addresses are used because they can easily be extended to
441 * IPv6 support. To separate the ranges, the return value from this
442 * function for an IPv6 address will be prefixed with "v6-", a non-
443 * hexadecimal string which sorts after the IPv4 addresses.
445 * @param $ip Quad dotted/octet IP address.
446 * @return hexidecimal
448 public static function toHex( $ip ) {
449 $n = self
::toUnsigned( $ip );
450 if ( $n !== false ) {
451 $n = self
::isIPv6( $ip ) ?
'v6-' . wfBaseConvert( $n, 10, 16, 32, false ) : wfBaseConvert( $n, 10, 16, 8, false );
457 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
458 * Like ip2long() except that it actually works and has a consistent error return value.
459 * Comes from ProxyTools.php
460 * @param $ip Quad dotted IP address.
463 public static function toUnsigned( $ip ) {
464 // Use IPv6 functions if needed
465 if ( self
::isIPv6( $ip ) ) {
466 return self
::toUnsigned6( $ip );
468 if ( $ip == '255.255.255.255' ) {
472 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
483 * Convert a dotted-quad IP to a signed integer
484 * Returns false on failure
486 public static function toSigned( $ip ) {
487 if ( $ip == '255.255.255.255' ) {
499 * Convert a network specification in CIDR notation to an integer network and a number of bits
500 * @return array(int, int)
502 public static function parseCIDR( $range ) {
503 $parts = explode( '/', $range, 2 );
504 if ( count( $parts ) != 2 ) {
505 return array( false, false );
507 list( $network, $bits ) = $parts;
508 $network = self
::toSigned( $network );
509 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
513 $network &= ~
( ( 1 << ( 32 - $bits ) ) - 1);
515 # Convert to unsigned
516 if ( $network < 0 ) {
517 $network +
= pow( 2, 32 );
523 return array( $network, $bits );
527 * Given a string range in a number of formats, return the start and end of
528 * the range in hexadecimal.
532 * 1.2.3.4 - 1.2.3.5 Explicit range
535 * 2001:0db8:85a3::7344/96 CIDR
536 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
537 * 2001:0db8:85a3::7344 Single IP
538 * @return array(string, int)
540 public static function parseRange( $range ) {
541 // Use IPv6 functions if needed
542 if ( self
::isIPv6( $range ) ) {
543 return self
::parseRange6( $range );
545 if ( strpos( $range, '/' ) !== false ) {
547 list( $network, $bits ) = self
::parseCIDR( $range );
548 if ( $network === false ) {
549 $start = $end = false;
551 $start = sprintf( '%08X', $network );
552 $end = sprintf( '%08X', $network +
pow( 2, ( 32 - $bits ) ) - 1 );
554 } elseif ( strpos( $range, '-' ) !== false ) {
556 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
557 if( self
::isIPAddress( $start ) && self
::isIPAddress( $end ) ) {
558 $start = self
::toUnsigned( $start );
559 $end = self
::toUnsigned( $end );
560 if ( $start > $end ) {
561 $start = $end = false;
563 $start = sprintf( '%08X', $start );
564 $end = sprintf( '%08X', $end );
567 $start = $end = false;
571 $start = $end = self
::toHex( $range );
573 if ( $start === false ||
$end === false ) {
574 return array( false, false );
576 return array( $start, $end );
581 * Determine if a given IPv4/IPv6 address is in a given CIDR network
582 * @param $addr The address to check against the given range.
583 * @param $range The range to check the given address against.
584 * @return bool Whether or not the given address is in the given range.
586 public static function isInRange( $addr, $range ) {
587 // Convert to IPv6 if needed
588 $hexIP = self
::toHex( $addr );
589 list( $start, $end ) = self
::parseRange( $range );
590 return ( strcmp( $hexIP, $start ) >= 0 &&
591 strcmp( $hexIP, $end ) <= 0 );
595 * Convert some unusual representations of IPv4 addresses to their
596 * canonical dotted quad representation.
598 * This currently only checks a few IPV4-to-IPv6 related cases. More
599 * unusual representations may be added later.
601 * @param $addr something that might be an IP address
602 * @return valid dotted quad IPv4 address or null
604 public static function canonicalize( $addr ) {
605 if ( self
::isValid( $addr ) ) {
609 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
610 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
611 $addr = substr( $addr, strrpos( $addr, ':' ) +
1 );
612 if( self
::isIPv4( $addr ) ) {
617 // IPv6 loopback address
619 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) ) {
623 // IPv4-mapped and IPv4-compatible IPv6 addresses
624 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) ) {
627 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) ) {
628 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
631 return null; // give up