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 Antoine Musso "<hashar at free dot fr>", Aaron Schulz
26 // Some regex definition to "play" with IP address and IP address blocks
28 // An IPv4 address is made of 4 bytes from x00 to xFF which is d0 to d255
29 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
30 define( 'RE_IP_ADD', RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
);
31 // An IPv4 block is an IP address and a prefix (d1 to d32)
32 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)' );
33 define( 'RE_IP_BLOCK', RE_IP_ADD
. '\/' . RE_IP_PREFIX
);
35 // An IPv6 address is made up of 8 words (each x0000 to xFFFF).
36 // However, the "::" abbreviation can be used on consecutive x0000 words.
37 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
38 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)' );
39 define( 'RE_IPV6_ADD',
40 '(?:' . // starts with "::" (including "::")
41 ':(?::|(?::' . RE_IPV6_WORD
. '){1,7})' .
42 '|' . // ends with "::" (except "::")
43 RE_IPV6_WORD
. '(?::' . RE_IPV6_WORD
. '){0,6}::' .
44 '|' . // contains one "::" in the middle (the ^ makes the test fail if none found)
45 RE_IPV6_WORD
. '(?::((?(-1)|:))?' . RE_IPV6_WORD
. '){1,6}(?(-2)|^)' .
46 '|' . // contains no "::"
47 RE_IPV6_WORD
. '(?::' . RE_IPV6_WORD
. '){7}' .
50 // An IPv6 block is an IP address and a prefix (d1 to d128)
51 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD
. '\/' . RE_IPV6_PREFIX
);
52 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
53 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
54 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP
. '(?:ffff:)?' );
56 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
57 define( 'IP_ADDRESS_STRING',
59 RE_IP_ADD
. '(?:\/' . RE_IP_PREFIX
. ')?' . // IPv4
61 RE_IPV6_ADD
. '(?:\/' . RE_IPV6_PREFIX
. ')?' . // IPv6
66 * A collection of public static functions to play with IP address
71 private static $proxyIpSet = null;
74 * Determine if a string is as valid IP address or network (CIDR prefix).
75 * SIIT IPv4-translated addresses are rejected.
76 * Note: canonicalize() tries to convert translated addresses to IPv4.
78 * @param string $ip Possible IP address
81 public static function isIPAddress( $ip ) {
82 return (bool)preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip );
86 * Given a string, determine if it as valid IP in IPv6 only.
87 * Note: Unlike isValid(), this looks for networks too.
89 * @param string $ip Possible IP address
92 public static function isIPv6( $ip ) {
93 return (bool)preg_match( '/^' . RE_IPV6_ADD
. '(?:\/' . RE_IPV6_PREFIX
. ')?$/', $ip );
97 * Given a string, determine if it as valid IP in IPv4 only.
98 * Note: Unlike isValid(), this looks for networks too.
100 * @param string $ip Possible IP address
103 public static function isIPv4( $ip ) {
104 return (bool)preg_match( '/^' . RE_IP_ADD
. '(?:\/' . RE_IP_PREFIX
. ')?$/', $ip );
108 * Validate an IP address. Ranges are NOT considered valid.
109 * SIIT IPv4-translated addresses are rejected.
110 * Note: canonicalize() tries to convert translated addresses to IPv4.
113 * @return bool True if it is valid
115 public static function isValid( $ip ) {
116 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip )
117 ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip ) );
121 * Validate an IP Block (valid address WITH a valid prefix).
122 * SIIT IPv4-translated addresses are rejected.
123 * Note: canonicalize() tries to convert translated addresses to IPv4.
125 * @param string $ipblock
126 * @return bool True if it is valid
128 public static function isValidBlock( $ipblock ) {
129 return ( preg_match( '/^' . RE_IPV6_BLOCK
. '$/', $ipblock )
130 ||
preg_match( '/^' . RE_IP_BLOCK
. '$/', $ipblock ) );
134 * Convert an IP into a verbose, uppercase, normalized form.
135 * IPv6 addresses in octet notation are expanded to 8 words.
136 * IPv4 addresses are just trimmed.
138 * @param string $ip IP address in quad or octet form (CIDR or not).
141 public static function sanitizeIP( $ip ) {
146 if ( self
::isIPv4( $ip ) ||
!self
::isIPv6( $ip ) ) {
147 return $ip; // nothing else to do for IPv4 addresses or invalid ones
149 // Remove any whitespaces, convert to upper case
150 $ip = strtoupper( $ip );
151 // Expand zero abbreviations
152 $abbrevPos = strpos( $ip, '::' );
153 if ( $abbrevPos !== false ) {
154 // We know this is valid IPv6. Find the last index of the
155 // address before any CIDR number (e.g. "a:b:c::/24").
156 $CIDRStart = strpos( $ip, "/" );
157 $addressEnd = ( $CIDRStart !== false )
160 // If the '::' is at the beginning...
161 if ( $abbrevPos == 0 ) {
163 $extra = ( $ip == '::' ) ?
'0' : ''; // for the address '::'
164 $pad = 9; // 7+2 (due to '::')
165 // If the '::' is at the end...
166 } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
169 $pad = 9; // 7+2 (due to '::')
170 // If the '::' is in the middle...
174 $pad = 8; // 6+2 (due to '::')
176 $ip = str_replace( '::',
177 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
181 // Remove leading zeros from each bloc as needed
182 $ip = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD
. ')/', '$1$2', $ip );
188 * Prettify an IP for display to end users.
189 * This will make it more compact and lower-case.
194 public static function prettifyIP( $ip ) {
195 $ip = self
::sanitizeIP( $ip ); // normalize (removes '::')
196 if ( self
::isIPv6( $ip ) ) {
197 // Split IP into an address and a CIDR
198 if ( strpos( $ip, '/' ) !== false ) {
199 list( $ip, $cidr ) = explode( '/', $ip, 2 );
201 list( $ip, $cidr ) = array( $ip, '' );
203 // Get the largest slice of words with multiple zeros
205 $longest = $longestPos = false;
207 '!(?:^|:)0(?::0)+(?:$|:)!', $ip, $m, PREG_OFFSET_CAPTURE
, $offset
209 list( $match, $pos ) = $m[0]; // full match
210 if ( strlen( $match ) > strlen( $longest ) ) {
214 $offset = ( $pos +
strlen( $match ) ); // advance
216 if ( $longest !== false ) {
217 // Replace this portion of the string with the '::' abbreviation
218 $ip = substr_replace( $ip, '::', $longestPos, strlen( $longest ) );
220 // Add any CIDR back on
221 if ( $cidr !== '' ) {
222 $ip = "{$ip}/{$cidr}";
224 // Convert to lower case to make it more readable
225 $ip = strtolower( $ip );
232 * Given a host/port string, like one might find in the host part of a URL
233 * per RFC 2732, split the hostname part and the port part and return an
234 * array with an element for each. If there is no port part, the array will
235 * have false in place of the port. If the string was invalid in some way,
238 * This was easy with IPv4 and was generally done in an ad-hoc way, but
239 * with IPv6 it's somewhat more complicated due to the need to parse the
240 * square brackets and colons.
242 * A bare IPv6 address is accepted despite the lack of square brackets.
244 * @param string $both The string with the host and port
245 * @return array|false Array normally, false on certain failures
247 public static function splitHostAndPort( $both ) {
248 if ( substr( $both, 0, 1 ) === '[' ) {
249 if ( preg_match( '/^\[(' . RE_IPV6_ADD
. ')\](?::(?P<port>\d+))?$/', $both, $m ) ) {
250 if ( isset( $m['port'] ) ) {
251 return array( $m[1], intval( $m['port'] ) );
253 return array( $m[1], false );
256 // Square bracket found but no IPv6
260 $numColons = substr_count( $both, ':' );
261 if ( $numColons >= 2 ) {
262 // Is it a bare IPv6 address?
263 if ( preg_match( '/^' . RE_IPV6_ADD
. '$/', $both ) ) {
264 return array( $both, false );
266 // Not valid IPv6, but too many colons for anything else
270 if ( $numColons >= 1 ) {
272 $bits = explode( ':', $both );
273 if ( preg_match( '/^\d+/', $bits[1] ) ) {
274 return array( $bits[0], intval( $bits[1] ) );
282 return array( $both, false );
286 * Given a host name and a port, combine them into host/port string like
287 * you might find in a URL. If the host contains a colon, wrap it in square
288 * brackets like in RFC 2732. If the port matches the default port, omit
289 * the port specification
291 * @param string $host
293 * @param bool|int $defaultPort
296 public static function combineHostAndPort( $host, $port, $defaultPort = false ) {
297 if ( strpos( $host, ':' ) !== false ) {
300 if ( $defaultPort !== false && $port == $defaultPort ) {
303 return "$host:$port";
308 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
310 * @param string $hex Number, with "v6-" prefix if it is IPv6
311 * @return string Quad-dotted (IPv4) or octet notation (IPv6)
313 public static function formatHex( $hex ) {
314 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
315 return self
::hexToOctet( substr( $hex, 3 ) );
317 return self
::hexToQuad( $hex );
322 * Converts a hexadecimal number to an IPv6 address in octet notation
324 * @param string $ip_hex Pure hex (no v6- prefix)
325 * @return string (of format a:b:c:d:e:f:g:h)
327 public static function hexToOctet( $ip_hex ) {
328 // Pad hex to 32 chars (128 bits)
329 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT
);
330 // Separate into 8 words
331 $ip_oct = substr( $ip_hex, 0, 4 );
332 for ( $n = 1; $n < 8; $n++
) {
333 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
336 $ip_oct = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD
. ')/', '$1$2', $ip_oct );
342 * Converts a hexadecimal number to an IPv4 address in quad-dotted notation
344 * @param string $ip_hex Pure hex
345 * @return string (of format a.b.c.d)
347 public static function hexToQuad( $ip_hex ) {
348 // Pad hex to 8 chars (32 bits)
349 $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT
);
350 // Separate into four quads
352 for ( $i = 0; $i < 4; $i++
) {
356 $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
363 * Determine if an IP address really is an IP address, and if it is public,
364 * i.e. not RFC 1918 or similar
369 public static function isPublic( $ip ) {
370 static $privateSet = null;
371 if ( !$privateSet ) {
372 $privateSet = new IPSet( array(
373 '10.0.0.0/8', # RFC 1918 (private)
374 '172.16.0.0/12', # RFC 1918 (private)
375 '192.168.0.0/16', # RFC 1918 (private)
376 '0.0.0.0/8', # this network
377 '127.0.0.0/8', # loopback
378 'fc00::/7', # RFC 4193 (local)
379 '0:0:0:0:0:0:0:1', # loopback
380 '169.254.0.0/16', # link-local
381 'fe80::/10', # link-local
384 return !$privateSet->match( $ip );
388 * Return a zero-padded upper case hexadecimal representation of an IP address.
390 * Hexadecimal addresses are used because they can easily be extended to
391 * IPv6 support. To separate the ranges, the return value from this
392 * function for an IPv6 address will be prefixed with "v6-", a non-
393 * hexadecimal string which sorts after the IPv4 addresses.
395 * @param string $ip Quad dotted/octet IP address.
396 * @return string|bool False on failure
398 public static function toHex( $ip ) {
399 if ( self
::isIPv6( $ip ) ) {
400 $n = 'v6-' . self
::IPv6ToRawHex( $ip );
401 } elseif ( self
::isIPv4( $ip ) ) {
402 // Bug 60035: an IP with leading 0's fails in ip2long sometimes (e.g. *.08)
403 $ip = preg_replace( '/(?<=\.)0+(?=[1-9])/', '', $ip );
407 # On 32-bit platforms (and on Windows), 2^32 does not fit into an int,
408 # so $n becomes a float. We convert it to string instead.
409 if ( is_float( $n ) ) {
413 if ( $n !== false ) {
414 # Floating points can handle the conversion; faster than wfBaseConvert()
415 $n = strtoupper( str_pad( base_convert( $n, 10, 16 ), 8, '0', STR_PAD_LEFT
) );
425 * Given an IPv6 address in octet notation, returns a pure hex string.
427 * @param string $ip Octet ipv6 IP address.
428 * @return string|bool Pure hex (uppercase); false on failure
430 private static function IPv6ToRawHex( $ip ) {
431 $ip = self
::sanitizeIP( $ip );
436 foreach ( explode( ':', $ip ) as $v ) {
437 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT
);
444 * Convert a network specification in CIDR notation
445 * to an integer network and a number of bits
447 * @param string $range IP with CIDR prefix
448 * @return array(int or string, int)
450 public static function parseCIDR( $range ) {
451 if ( self
::isIPv6( $range ) ) {
452 return self
::parseCIDR6( $range );
454 $parts = explode( '/', $range, 2 );
455 if ( count( $parts ) != 2 ) {
456 return array( false, false );
458 list( $network, $bits ) = $parts;
459 $network = ip2long( $network );
460 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
464 $network &= ~
( ( 1 << ( 32 - $bits ) ) - 1 );
466 # Convert to unsigned
467 if ( $network < 0 ) {
468 $network +
= pow( 2, 32 );
475 return array( $network, $bits );
479 * Given a string range in a number of formats,
480 * return the start and end of the range in hexadecimal.
484 * 1.2.3.4 - 1.2.3.5 Explicit range
487 * 2001:0db8:85a3::7344/96 CIDR
488 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
489 * 2001:0db8:85a3::7344 Single IP
490 * @param string $range IP range
491 * @return array(string, string)
493 public static function parseRange( $range ) {
495 if ( strpos( $range, '/' ) !== false ) {
496 if ( self
::isIPv6( $range ) ) {
497 return self
::parseRange6( $range );
499 list( $network, $bits ) = self
::parseCIDR( $range );
500 if ( $network === false ) {
501 $start = $end = false;
503 $start = sprintf( '%08X', $network );
504 $end = sprintf( '%08X', $network +
pow( 2, ( 32 - $bits ) ) - 1 );
507 } elseif ( strpos( $range, '-' ) !== false ) {
508 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
509 if ( self
::isIPv6( $start ) && self
::isIPv6( $end ) ) {
510 return self
::parseRange6( $range );
512 if ( self
::isIPv4( $start ) && self
::isIPv4( $end ) ) {
513 $start = self
::toHex( $start );
514 $end = self
::toHex( $end );
515 if ( $start > $end ) {
516 $start = $end = false;
519 $start = $end = false;
523 $start = $end = self
::toHex( $range );
525 if ( $start === false ||
$end === false ) {
526 return array( false, false );
528 return array( $start, $end );
533 * Convert a network specification in IPv6 CIDR notation to an
534 * integer network and a number of bits
536 * @param string $range
538 * @return array(string, int)
540 private static function parseCIDR6( $range ) {
541 # Explode into <expanded IP,range>
542 $parts = explode( '/', IP
::sanitizeIP( $range ), 2 );
543 if ( count( $parts ) != 2 ) {
544 return array( false, false );
546 list( $network, $bits ) = $parts;
547 $network = self
::IPv6ToRawHex( $network );
548 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
552 # Native 32 bit functions WONT work here!!!
553 # Convert to a padded binary number
554 $network = wfBaseConvert( $network, 16, 2, 128 );
555 # Truncate the last (128-$bits) bits and replace them with zeros
556 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
557 # Convert back to an integer
558 $network = wfBaseConvert( $network, 2, 10 );
565 return array( $network, (int)$bits );
569 * Given a string range in a number of formats, return the
570 * start and end of the range in hexadecimal. For IPv6.
573 * 2001:0db8:85a3::7344/96 CIDR
574 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
575 * 2001:0db8:85a3::7344/96 Single IP
577 * @param string $range
579 * @return array(string, string)
581 private static function parseRange6( $range ) {
583 $range = IP
::sanitizeIP( $range );
585 if ( strpos( $range, '/' ) !== false ) {
586 list( $network, $bits ) = self
::parseCIDR6( $range );
587 if ( $network === false ) {
588 $start = $end = false;
590 $start = wfBaseConvert( $network, 10, 16, 32, false );
591 # Turn network to binary (again)
592 $end = wfBaseConvert( $network, 10, 2, 128 );
593 # Truncate the last (128-$bits) bits and replace them with ones
594 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT
);
596 $end = wfBaseConvert( $end, 2, 16, 32, false );
597 # see toHex() comment
598 $start = "v6-$start";
601 // Explicit range notation...
602 } elseif ( strpos( $range, '-' ) !== false ) {
603 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
604 $start = self
::toHex( $start );
605 $end = self
::toHex( $end );
606 if ( $start > $end ) {
607 $start = $end = false;
611 $start = $end = self
::toHex( $range );
613 if ( $start === false ||
$end === false ) {
614 return array( false, false );
616 return array( $start, $end );
621 * Determine if a given IPv4/IPv6 address is in a given CIDR network
623 * @param string $addr The address to check against the given range.
624 * @param string $range The range to check the given address against.
625 * @return bool Whether or not the given address is in the given range.
627 public static function isInRange( $addr, $range ) {
628 $hexIP = self
::toHex( $addr );
629 list( $start, $end ) = self
::parseRange( $range );
631 return ( strcmp( $hexIP, $start ) >= 0 &&
632 strcmp( $hexIP, $end ) <= 0 );
636 * Determines if an IP address is a list of CIDR a.b.c.d/n ranges.
640 * @param string $ip the IP to check
641 * @param array $ranges the IP ranges, each element a range
643 * @return bool true if the specified adress belongs to the specified range; otherwise, false.
645 public static function isInRanges( $ip, $ranges ) {
646 foreach ( $ranges as $range ) {
647 if ( self
::isInRange( $ip, $range ) ) {
655 * Convert some unusual representations of IPv4 addresses to their
656 * canonical dotted quad representation.
658 * This currently only checks a few IPV4-to-IPv6 related cases. More
659 * unusual representations may be added later.
661 * @param string $addr Something that might be an IP address
662 * @return string|null Valid dotted quad IPv4 address or null
664 public static function canonicalize( $addr ) {
665 // remove zone info (bug 35738)
666 $addr = preg_replace( '/\%.*/', '', $addr );
668 if ( self
::isValid( $addr ) ) {
671 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
672 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
673 $addr = substr( $addr, strrpos( $addr, ':' ) +
1 );
674 if ( self
::isIPv4( $addr ) ) {
678 // IPv6 loopback address
680 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) ) {
683 // IPv4-mapped and IPv4-compatible IPv6 addresses
684 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) ) {
687 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
.
688 ':' . RE_IPV6_WORD
. '$/i', $addr, $m )
690 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
693 return null; // give up
697 * Gets rid of unneeded numbers in quad-dotted/octet IP strings
698 * For example, 127.111.113.151/24 -> 127.111.113.0/24
699 * @param string $range IP address to normalize
702 public static function sanitizeRange( $range ) {
703 list( /*...*/, $bits ) = self
::parseCIDR( $range );
704 list( $start, /*...*/ ) = self
::parseRange( $range );
705 $start = self
::formatHex( $start );
706 if ( $bits === false ) {
707 return $start; // wasn't actually a range
710 return "$start/$bits";
714 * Checks if an IP is a trusted proxy provider.
715 * Useful to tell if X-Forwarded-For data is possibly bogus.
716 * Squid cache servers for the site are whitelisted.
722 public static function isTrustedProxy( $ip ) {
723 $trusted = self
::isConfiguredProxy( $ip );
724 Hooks
::run( 'IsTrustedProxy', array( &$ip, &$trusted ) );
729 * Checks if an IP matches a proxy we've configured
735 public static function isConfiguredProxy( $ip ) {
736 global $wgSquidServers, $wgSquidServersNoPurge;
738 // Quick check of known singular proxy servers
739 $trusted = in_array( $ip, $wgSquidServers );
741 // Check against addresses and CIDR nets in the NoPurge list
743 if ( !self
::$proxyIpSet ) {
744 self
::$proxyIpSet = new IPSet( $wgSquidServersNoPurge );
746 $trusted = self
::$proxyIpSet->match( $ip );
753 * Clears precomputed data used for proxy support.
754 * Use this only for unit tests.
756 public static function clearCaches() {
757 self
::$proxyIpSet = null;