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>, Aaron Schulz
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
);
33 // An IPv6 block is an IP address and a prefix (d1 to d128)
34 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
35 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
36 // An IPv6 address is made up of 8 words. However, the "::" abbreviation can be used.
37 define( 'RE_IPV6_ADD',
38 '(' . // starts with "::" (includes the address "::")
39 '(::|:(:' . RE_IPV6_WORD
. '){1,7})' .
40 '|' . // ends with "::" (not including the address "::")
41 RE_IPV6_WORD
. '(:' . RE_IPV6_WORD
. '){0,6}::' .
43 RE_IPV6_WORD
. '(:' . RE_IPV6_WORD
. '){7}' .
44 '|' . // contains one "::" in the middle ("^" check always fails if no "::" found)
45 RE_IPV6_WORD
. '(:(?P<abbr>(?(abbr)|:))?' . RE_IPV6_WORD
. '){1,6}(?(abbr)|^)' .
48 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD
. '\/' . RE_IPV6_PREFIX
);
49 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
50 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
51 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP
. '(?:ffff:)?' );
53 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
54 define( 'IP_ADDRESS_STRING',
56 RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)' . // IPv4
58 RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)' . // IPv6
63 * A collection of public static functions to play with IP address
68 * Determine if a string is as valid IP address or network (CIDR prefix).
69 * SIIT IPv4-translated addresses are rejected.
70 * Note: canonicalize() tries to convert translated addresses to IPv4.
71 * @param string $ip possible IP address
74 public static function isIPAddress( $ip ) {
75 return (bool)preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip );
79 * Given a string, determine if it as valid IP in IPv6 only.
80 * Note: Unlike isValid(), this looks for networks too.
81 * @param string $ip possible IP address
84 public static function isIPv6( $ip ) {
85 return (bool)preg_match( '/^' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)$/', $ip );
89 * Given a string, determine if it as valid IP in IPv4 only.
90 * Note: Unlike isValid(), this looks for networks too.
91 * @param string $ip possible IP address
94 public static function isIPv4( $ip ) {
95 return (bool)preg_match( '/^' . RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)$/', $ip );
99 * Validate an IP address. Ranges are NOT considered valid.
100 * SIIT IPv4-translated addresses are rejected.
101 * Note: canonicalize() tries to convert translated addresses to IPv4.
103 * @return boolean True if it is valid.
105 public static function isValid( $ip ) {
106 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip )
107 ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip ) );
111 * Validate an IP Block (valid address WITH a valid prefix).
112 * SIIT IPv4-translated addresses are rejected.
113 * Note: canonicalize() tries to convert translated addresses to IPv4.
114 * @param string $ipblock
115 * @return boolean True if it is valid.
117 public static function isValidBlock( $ipblock ) {
118 return ( preg_match( '/^' . RE_IPV6_BLOCK
. '$/', $ipblock )
119 ||
preg_match( '/^' . RE_IPV4_BLOCK
. '$/', $ipblock ) );
123 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
124 * See http://www.answers.com/topic/ipv4-compatible-address
125 * IPs with the first 92 bits as zeros are reserved from IPv6
126 * @param string $ip quad-dotted IP address.
127 * @return string IPv4 address
129 public static function IPv4toIPv6( $ip ) {
130 if ( !self
::isIPv4( $ip ) ) {
131 throw new MWException( "IPv4toIPv6() called on a non-IPv4 address." );
133 // IPv4 address with CIDR
134 if ( strpos( $ip, '/' ) !== false ) {
135 $parts = explode( '/', $ip, 2 );
136 if ( count( $parts ) != 2 ) {
139 list( $network, $bits ) = $parts;
140 $network = self
::toUnsigned( $network );
141 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
143 return self
::toOctet( $network ) . "/$bits";
148 return self
::toOctet( self
::toUnsigned( $ip ) );
152 * Convert an IP into a nice standard form.
153 * IPv6 addresses in octet notation are expanded to 8 words.
154 * IPv4 addresses are just trimmed.
155 * @param string $ip IP address in quad or octet form (CIDR or not).
158 public static function sanitizeIP( $ip ) {
163 if ( self
::isIPv4( $ip ) ||
!self
::isIPv6( $ip ) ) {
164 return $ip; // nothing else to do for IPv4 addresses or invalid ones
166 // Remove any whitespaces, convert to upper case
167 $ip = strtoupper( $ip );
168 // Expand zero abbreviations
169 $abbrevPos = strpos( $ip, '::' );
170 if ( $abbrevPos !== false ) {
171 // We know this is valid IPv6. Find the last index of the
172 // address before any CIDR number (e.g. "a:b:c::/24").
173 $CIDRStart = strpos( $ip, "/" );
174 $addressEnd = ( $CIDRStart !== false )
177 // If the '::' is at the beginning...
178 if ( $abbrevPos == 0 ) {
180 $extra = ( $ip == '::' ) ?
'0' : ''; // for the address '::'
181 $pad = 9; // 7+2 (due to '::')
182 // If the '::' is at the end...
183 } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
186 $pad = 9; // 7+2 (due to '::')
187 // If the '::' is in the middle...
191 $pad = 8; // 6+2 (due to '::')
193 $ip = str_replace( '::',
194 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
198 // Remove leading zereos from each bloc as needed
199 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip );
204 * Given an unsigned integer, returns an IPv6 address in octet notation
205 * @param string $ip_int IP address.
208 public static function toOctet( $ip_int ) {
209 return self
::hexToOctet( wfBaseConvert( $ip_int, 10, 16, 32, false ) );
213 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
214 * @param string $hex number, with "v6-" prefix if it is IPv6
215 * @return string quad-dotted (IPv4) or octet notation (IPv6)
217 public static function formatHex( $hex ) {
218 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
219 return self
::hexToOctet( substr( $hex, 3 ) );
221 return self
::hexToQuad( $hex );
226 * Converts a hexadecimal number to an IPv6 address in octet notation
227 * @param string $ip_hex pure hex (no v6- prefix)
228 * @return string (of format a:b:c:d:e:f:g:h)
230 public static function hexToOctet( $ip_hex ) {
231 // Pad hex to 32 chars (128 bits)
232 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT
);
233 // Separate into 8 words
234 $ip_oct = substr( $ip_hex, 0, 4 );
235 for ( $n = 1; $n < 8; $n++
) {
236 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
239 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip_oct );
244 * Converts a hexadecimal number to an IPv4 address in quad-dotted notation
245 * @param string $ip_hex pure hex
246 * @return string (of format a.b.c.d)
248 public static function hexToQuad( $ip_hex ) {
249 // Pad hex to 8 chars (32 bits)
250 $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT
);
251 // Separate into four quads
253 for ( $i = 0; $i < 4; $i++
) {
257 $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
263 * Determine if an IP address really is an IP address, and if it is public,
264 * i.e. not RFC 1918 or similar
265 * Comes from ProxyTools.php
269 public static function isPublic( $ip ) {
270 if ( self
::isIPv6( $ip ) ) {
271 return self
::isPublic6( $ip );
273 $n = self
::toUnsigned( $ip );
278 // ip2long accepts incomplete addresses, as well as some addresses
279 // followed by garbage characters. Check that it's really valid.
280 if ( $ip != long2ip( $n ) ) {
284 static $privateRanges = false;
285 if ( !$privateRanges ) {
286 $privateRanges = array(
287 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
288 array( '172.16.0.0', '172.31.255.255' ), # "
289 array( '192.168.0.0', '192.168.255.255' ), # "
290 array( '0.0.0.0', '0.255.255.255' ), # this network
291 array( '127.0.0.0', '127.255.255.255' ), # loopback
295 foreach ( $privateRanges as $r ) {
296 $start = self
::toUnsigned( $r[0] );
297 $end = self
::toUnsigned( $r[1] );
298 if ( $n >= $start && $n <= $end ) {
306 * Determine if an IPv6 address really is an IP address, and if it is public,
307 * i.e. not RFC 4193 or similar
311 private static function isPublic6( $ip ) {
312 static $privateRanges = false;
313 if ( !$privateRanges ) {
314 $privateRanges = array(
315 array( 'fc::', 'fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' ), # RFC 4193 (local)
316 array( '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1' ), # loopback
319 $n = self
::toHex( $ip );
320 foreach ( $privateRanges as $r ) {
321 $start = self
::toHex( $r[0] );
322 $end = self
::toHex( $r[1] );
323 if ( $n >= $start && $n <= $end ) {
331 * Return a zero-padded upper case hexadecimal representation of an IP address.
333 * Hexadecimal addresses are used because they can easily be extended to
334 * IPv6 support. To separate the ranges, the return value from this
335 * function for an IPv6 address will be prefixed with "v6-", a non-
336 * hexadecimal string which sorts after the IPv4 addresses.
338 * @param string $ip Quad dotted/octet IP address.
341 public static function toHex( $ip ) {
342 if ( self
::isIPv6( $ip ) ) {
343 $n = 'v6-' . self
::IPv6ToRawHex( $ip );
345 $n = self
::toUnsigned( $ip );
346 if ( $n !== false ) {
347 $n = wfBaseConvert( $n, 10, 16, 8, false );
354 * Given an IPv6 address in octet notation, returns a pure hex string.
355 * @param string $ip octet ipv6 IP address.
356 * @return string pure hex (uppercase)
358 private static function IPv6ToRawHex( $ip ) {
359 $ip = self
::sanitizeIP( $ip );
364 foreach ( explode( ':', $ip ) as $v ) {
365 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT
);
371 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
372 * Like ip2long() except that it actually works and has a consistent error return value.
373 * Comes from ProxyTools.php
374 * @param string $ip Quad dotted IP address.
375 * @return mixed (string/int/false)
377 public static function toUnsigned( $ip ) {
378 if ( self
::isIPv6( $ip ) ) {
379 $n = self
::toUnsigned6( $ip );
389 private static function toUnsigned6( $ip ) {
390 return wfBaseConvert( self
::IPv6ToRawHex( $ip ), 16, 10 );
394 * Convert a network specification in CIDR notation
395 * to an integer network and a number of bits
396 * @param string $range IP with CIDR prefix
397 * @return array(int or string, int)
399 public static function parseCIDR( $range ) {
400 if ( self
::isIPv6( $range ) ) {
401 return self
::parseCIDR6( $range );
403 $parts = explode( '/', $range, 2 );
404 if ( count( $parts ) != 2 ) {
405 return array( false, false );
407 list( $network, $bits ) = $parts;
408 $network = ip2long( $network );
409 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
413 $network &= ~
( ( 1 << ( 32 - $bits ) ) - 1);
415 # Convert to unsigned
416 if ( $network < 0 ) {
417 $network +
= pow( 2, 32 );
423 return array( $network, $bits );
427 * Given a string range in a number of formats,
428 * return the start and end of the range in hexadecimal.
432 * 1.2.3.4 - 1.2.3.5 Explicit range
435 * 2001:0db8:85a3::7344/96 CIDR
436 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
437 * 2001:0db8:85a3::7344 Single IP
438 * @param string $range IP range
439 * @return array(string, string)
441 public static function parseRange( $range ) {
443 if ( strpos( $range, '/' ) !== false ) {
444 if ( self
::isIPv6( $range ) ) {
445 return self
::parseRange6( $range );
447 list( $network, $bits ) = self
::parseCIDR( $range );
448 if ( $network === false ) {
449 $start = $end = false;
451 $start = sprintf( '%08X', $network );
452 $end = sprintf( '%08X', $network +
pow( 2, ( 32 - $bits ) ) - 1 );
455 } elseif ( strpos( $range, '-' ) !== false ) {
456 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
457 if ( self
::isIPv6( $start ) && self
::isIPv6( $end ) ) {
458 return self
::parseRange6( $range );
460 if ( self
::isIPv4( $start ) && self
::isIPv4( $end ) ) {
461 $start = self
::toUnsigned( $start );
462 $end = self
::toUnsigned( $end );
463 if ( $start > $end ) {
464 $start = $end = false;
466 $start = sprintf( '%08X', $start );
467 $end = sprintf( '%08X', $end );
470 $start = $end = false;
474 $start = $end = self
::toHex( $range );
476 if ( $start === false ||
$end === false ) {
477 return array( false, false );
479 return array( $start, $end );
484 * Convert a network specification in IPv6 CIDR notation to an
485 * integer network and a number of bits
486 * @return array(string, int)
488 private static function parseCIDR6( $range ) {
489 # Explode into <expanded IP,range>
490 $parts = explode( '/', IP
::sanitizeIP( $range ), 2 );
491 if ( count( $parts ) != 2 ) {
492 return array( false, false );
494 list( $network, $bits ) = $parts;
495 $network = self
::IPv6ToRawHex( $network );
496 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
500 # Native 32 bit functions WONT work here!!!
501 # Convert to a padded binary number
502 $network = wfBaseConvert( $network, 16, 2, 128 );
503 # Truncate the last (128-$bits) bits and replace them with zeros
504 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
505 # Convert back to an integer
506 $network = wfBaseConvert( $network, 2, 10 );
512 return array( $network, (int)$bits );
516 * Given a string range in a number of formats, return the
517 * start and end of the range in hexadecimal. For IPv6.
520 * 2001:0db8:85a3::7344/96 CIDR
521 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
522 * 2001:0db8:85a3::7344/96 Single IP
523 * @return array(string, string)
525 private static function parseRange6( $range ) {
527 $range = IP
::sanitizeIP( $range );
529 if ( strpos( $range, '/' ) !== false ) {
530 list( $network, $bits ) = self
::parseCIDR6( $range );
531 if ( $network === false ) {
532 $start = $end = false;
534 $start = wfBaseConvert( $network, 10, 16, 32, false );
535 # Turn network to binary (again)
536 $end = wfBaseConvert( $network, 10, 2, 128 );
537 # Truncate the last (128-$bits) bits and replace them with ones
538 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT
);
540 $end = wfBaseConvert( $end, 2, 16, 32, false );
541 # see toHex() comment
542 $start = "v6-$start";
545 // Explicit range notation...
546 } elseif ( strpos( $range, '-' ) !== false ) {
547 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
548 $start = self
::toUnsigned6( $start );
549 $end = self
::toUnsigned6( $end );
550 if ( $start > $end ) {
551 $start = $end = false;
553 $start = wfBaseConvert( $start, 10, 16, 32, false );
554 $end = wfBaseConvert( $end, 10, 16, 32, false );
556 # see toHex() comment
557 $start = "v6-$start";
561 $start = $end = self
::toHex( $range );
563 if ( $start === false ||
$end === false ) {
564 return array( false, false );
566 return array( $start, $end );
571 * Determine if a given IPv4/IPv6 address is in a given CIDR network
572 * @param $addr The address to check against the given range.
573 * @param $range The range to check the given address against.
574 * @return bool Whether or not the given address is in the given range.
576 public static function isInRange( $addr, $range ) {
577 $hexIP = self
::toHex( $addr );
578 list( $start, $end ) = self
::parseRange( $range );
579 return ( strcmp( $hexIP, $start ) >= 0 &&
580 strcmp( $hexIP, $end ) <= 0 );
584 * Convert some unusual representations of IPv4 addresses to their
585 * canonical dotted quad representation.
587 * This currently only checks a few IPV4-to-IPv6 related cases. More
588 * unusual representations may be added later.
590 * @param $addr something that might be an IP address
591 * @return valid dotted quad IPv4 address or null
593 public static function canonicalize( $addr ) {
594 if ( self
::isValid( $addr ) ) {
597 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
598 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
599 $addr = substr( $addr, strrpos( $addr, ':' ) +
1 );
600 if ( self
::isIPv4( $addr ) ) {
604 // IPv6 loopback address
606 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) ) {
609 // IPv4-mapped and IPv4-compatible IPv6 addresses
610 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) ) {
613 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
.
614 ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
616 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
619 return null; // give up