]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/IP.php
MediaWiki 1.17.0
[autoinstalls/mediawiki.git] / includes / IP.php
1 <?php
2 /**
3  * Functions and constants to play with IP addresses and ranges
4  *
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.
9  *
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.
14  *
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
19  *
20  * @file
21  * @author Ashar Voultoiz <hashar at free dot fr>, Aaron Schulz
22  */
23
24 // Some regex definition to "play" with IP address and IP address blocks
25
26 // An IPv4 address 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
33 // An IPv6 address is made up of 8 words (each x0000 to xFFFF).
34 // However, the "::" abbreviation can be used on consecutive x0000 words.
35 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
36 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
37 define( 'RE_IPV6_ADD',
38         '(?:' . // starts with "::" (including "::")
39                 ':(?::|(?::' . RE_IPV6_WORD . '){1,7})' .
40         '|' . // ends with "::" (except "::")
41                 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){0,6}::' .
42         '|' . // contains one "::" in the middle, ending in "::WORD"
43                 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){0,5}' . '::' . RE_IPV6_WORD .
44         '|' . // contains one "::" in the middle, not ending in "::WORD" (regex for PCRE 4.0+)
45                 RE_IPV6_WORD . '(?::(?P<abn>:(?P<iabn>))?' . RE_IPV6_WORD . '(?!:(?P=abn))){1,5}' .
46                         ':' . RE_IPV6_WORD . '(?P=iabn)' .
47                 // NOTE: (?!(?P=abn)) fails iff "::" used twice; (?P=iabn) passes iff a "::" was found.
48         '|' . // contains no "::"
49                 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){7}' .
50         ')'
51         // NOTE: With PCRE 7.2+, we can combine the two '"::" in the middle' cases into:
52         //              RE_IPV6_WORD . '(?::((?(-1)|:))?' . RE_IPV6_WORD . '){1,6}(?(-2)|^)'
53         // This also improves regex concatenation by using relative references.
54 );
55 // An IPv6 block is an IP address and a prefix (d1 to d128)
56 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
57 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
58 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
59 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
60
61 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
62 define( 'IP_ADDRESS_STRING',
63         '(?:' .
64                 RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?' . // IPv4
65         '|' .
66                 RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?' . // IPv6
67         ')'
68 );
69
70 /**
71  * A collection of public static functions to play with IP address
72  * and IP blocks.
73  */
74 class IP {
75         /**
76          * Determine if a string is as valid IP address or network (CIDR prefix).
77          * SIIT IPv4-translated addresses are rejected.
78          * Note: canonicalize() tries to convert translated addresses to IPv4.
79          *
80          * @param $ip String: possible IP address
81          * @return Boolean
82          */
83         public static function isIPAddress( $ip ) {
84                 return (bool)preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip );
85         }
86
87         /**
88          * Given a string, determine if it as valid IP in IPv6 only.
89          * Note: Unlike isValid(), this looks for networks too.
90          *
91          * @param $ip String: possible IP address
92          * @return Boolean
93          */
94         public static function isIPv6( $ip ) {
95                 return (bool)preg_match( '/^' . RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?$/', $ip );
96         }
97
98         /**
99          * Given a string, determine if it as valid IP in IPv4 only.
100          * Note: Unlike isValid(), this looks for networks too.
101          *
102          * @param $ip String: possible IP address
103          * @return Boolean
104          */
105         public static function isIPv4( $ip ) {
106                 return (bool)preg_match( '/^' . RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?$/', $ip );
107         }
108
109         /**
110          * Validate an IP address. Ranges are NOT considered valid.
111          * SIIT IPv4-translated addresses are rejected.
112          * Note: canonicalize() tries to convert translated addresses to IPv4.
113          *
114          * @param $ip String
115          * @return Boolean: True if it is valid.
116          */
117         public static function isValid( $ip ) {
118                 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip )
119                         || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip ) );
120         }
121
122         /**
123          * Validate an IP Block (valid address WITH a valid prefix).
124          * SIIT IPv4-translated addresses are rejected.
125          * Note: canonicalize() tries to convert translated addresses to IPv4.
126          *
127          * @param $ipblock String
128          * @return Boolean: True if it is valid.
129          */
130         public static function isValidBlock( $ipblock ) {
131                 return ( preg_match( '/^' . RE_IPV6_BLOCK . '$/', $ipblock )
132                         || preg_match( '/^' . RE_IP_BLOCK . '$/', $ipblock ) );
133         }
134
135         /**
136          * Convert an IP into a nice standard form.
137          * IPv6 addresses in octet notation are expanded to 8 words.
138          * IPv4 addresses are just trimmed.
139          *
140          * @param $ip String: IP address in quad or octet form (CIDR or not).
141          * @return String
142          */
143         public static function sanitizeIP( $ip ) {
144                 $ip = trim( $ip );
145                 if ( $ip === '' ) {
146                         return null;
147                 }
148                 if ( self::isIPv4( $ip ) || !self::isIPv6( $ip ) ) {
149                         return $ip; // nothing else to do for IPv4 addresses or invalid ones
150                 }
151                 // Remove any whitespaces, convert to upper case
152                 $ip = strtoupper( $ip );
153                 // Expand zero abbreviations
154                 $abbrevPos = strpos( $ip, '::' );
155                 if ( $abbrevPos !== false ) {
156                         // We know this is valid IPv6. Find the last index of the
157                         // address before any CIDR number (e.g. "a:b:c::/24").
158                         $CIDRStart = strpos( $ip, "/" );
159                         $addressEnd = ( $CIDRStart !== false )
160                                 ? $CIDRStart - 1
161                                 : strlen( $ip ) - 1;
162                         // If the '::' is at the beginning...
163                         if ( $abbrevPos == 0 ) {
164                                 $repeat = '0:';
165                                 $extra = ( $ip == '::' ) ? '0' : ''; // for the address '::'
166                                 $pad = 9; // 7+2 (due to '::')
167                         // If the '::' is at the end...
168                         } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
169                                 $repeat = ':0';
170                                 $extra = '';
171                                 $pad = 9; // 7+2 (due to '::')
172                         // If the '::' is in the middle...
173                         } else {
174                                 $repeat = ':0';
175                                 $extra = ':';
176                                 $pad = 8; // 6+2 (due to '::')
177                         }
178                         $ip = str_replace( '::',
179                                 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
180                                 $ip
181                         );
182                 }
183                 // Remove leading zereos from each bloc as needed
184                 $ip = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip );
185                 return $ip;
186         }
187
188         /**
189          * Given an unsigned integer, returns an IPv6 address in octet notation
190          *
191          * @param $ip_int String: IP address.
192          * @return String
193          */
194         public static function toOctet( $ip_int ) {
195                 return self::hexToOctet( wfBaseConvert( $ip_int, 10, 16, 32, false ) );
196         }
197
198         /**
199          * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
200          *
201          * @param $hex String: number, with "v6-" prefix if it is IPv6
202          * @return String: quad-dotted (IPv4) or octet notation (IPv6)
203          */
204         public static function formatHex( $hex ) {
205                 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
206                         return self::hexToOctet( substr( $hex, 3 ) );
207                 } else { // IPv4
208                         return self::hexToQuad( $hex );
209                 }
210         }
211
212         /**
213          * Converts a hexadecimal number to an IPv6 address in octet notation
214          *
215          * @param $ip_hex String: pure hex (no v6- prefix)
216          * @return String (of format a:b:c:d:e:f:g:h)
217          */
218         public static function hexToOctet( $ip_hex ) {
219                 // Pad hex to 32 chars (128 bits)
220                 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT );
221                 // Separate into 8 words
222                 $ip_oct = substr( $ip_hex, 0, 4 );
223                 for ( $n = 1; $n < 8; $n++ ) {
224                         $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
225                 }
226                 // NO leading zeroes
227                 $ip_oct = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip_oct );
228                 return $ip_oct;
229         }
230
231         /**
232          * Converts a hexadecimal number to an IPv4 address in quad-dotted notation
233          *
234          * @param $ip_hex String: pure hex
235          * @return String (of format a.b.c.d)
236          */
237         public static function hexToQuad( $ip_hex ) {
238                 // Pad hex to 8 chars (32 bits)
239                 $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT );
240                 // Separate into four quads
241                 $s = '';
242                 for ( $i = 0; $i < 4; $i++ ) {
243                         if ( $s !== '' ) {
244                                 $s .= '.';
245                         }
246                         $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
247                 }
248                 return $s;
249         }
250
251         /**
252          * Determine if an IP address really is an IP address, and if it is public,
253          * i.e. not RFC 1918 or similar
254          * Comes from ProxyTools.php
255          *
256          * @param $ip String
257          * @return Boolean
258          */
259         public static function isPublic( $ip ) {
260                 if ( self::isIPv6( $ip ) ) {
261                         return self::isPublic6( $ip );
262                 }
263                 $n = self::toUnsigned( $ip );
264                 if ( !$n ) {
265                         return false;
266                 }
267
268                 // ip2long accepts incomplete addresses, as well as some addresses
269                 // followed by garbage characters. Check that it's really valid.
270                 if ( $ip != long2ip( $n ) ) {
271                         return false;
272                 }
273
274                 static $privateRanges = false;
275                 if ( !$privateRanges ) {
276                         $privateRanges = array(
277                                 array( '10.0.0.0',    '10.255.255.255' ),   # RFC 1918 (private)
278                                 array( '172.16.0.0',  '172.31.255.255' ),   #     "
279                                 array( '192.168.0.0', '192.168.255.255' ),  #     "
280                                 array( '0.0.0.0',     '0.255.255.255' ),    # this network
281                                 array( '127.0.0.0',   '127.255.255.255' ),  # loopback
282                         );
283                 }
284
285                 foreach ( $privateRanges as $r ) {
286                         $start = self::toUnsigned( $r[0] );
287                         $end = self::toUnsigned( $r[1] );
288                         if ( $n >= $start && $n <= $end ) {
289                                 return false;
290                         }
291                 }
292                 return true;
293         }
294
295         /**
296          * Determine if an IPv6 address really is an IP address, and if it is public,
297          * i.e. not RFC 4193 or similar
298          *
299          * @param $ip String
300          * @return Boolean
301          */
302         private static function isPublic6( $ip ) {
303                 static $privateRanges = false;
304                 if ( !$privateRanges ) {
305                         $privateRanges = array(
306                                 array( 'fc::', 'fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' ), # RFC 4193 (local)
307                                 array( '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1' ), # loopback
308                         );
309                 }
310                 $n = self::toHex( $ip );
311                 foreach ( $privateRanges as $r ) {
312                         $start = self::toHex( $r[0] );
313                         $end = self::toHex( $r[1] );
314                         if ( $n >= $start && $n <= $end ) {
315                                 return false;
316                         }
317                 }
318                 return true;
319         }
320
321         /**
322          * Return a zero-padded upper case hexadecimal representation of an IP address.
323          *
324          * Hexadecimal addresses are used because they can easily be extended to
325          * IPv6 support. To separate the ranges, the return value from this
326          * function for an IPv6 address will be prefixed with "v6-", a non-
327          * hexadecimal string which sorts after the IPv4 addresses.
328          *
329          * @param $ip String: quad dotted/octet IP address.
330          * @return String
331          */
332         public static function toHex( $ip ) {
333                 if ( self::isIPv6( $ip ) ) {
334                         $n = 'v6-' . self::IPv6ToRawHex( $ip );
335                 } else {
336                         $n = self::toUnsigned( $ip );
337                         if ( $n !== false ) {
338                                 $n = wfBaseConvert( $n, 10, 16, 8, false );
339                         }
340                 }
341                 return $n;
342         }
343
344         /**
345          * Given an IPv6 address in octet notation, returns a pure hex string.
346          *
347          * @param $ip String: octet ipv6 IP address.
348          * @return String: pure hex (uppercase)
349          */
350         private static function IPv6ToRawHex( $ip ) {
351                 $ip = self::sanitizeIP( $ip );
352                 if ( !$ip ) {
353                         return null;
354                 }
355                 $r_ip = '';
356                 foreach ( explode( ':', $ip ) as $v ) {
357                         $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
358                 }
359                 return $r_ip;
360         }
361
362         /**
363          * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
364          * Like ip2long() except that it actually works and has a consistent error return value.
365          * Comes from ProxyTools.php
366          *
367          * @param $ip String: quad dotted IP address.
368          * @return Mixed: string/int/false
369          */
370         public static function toUnsigned( $ip ) {
371                 if ( self::isIPv6( $ip ) ) {
372                         $n = self::toUnsigned6( $ip );
373                 } else {
374                         $n = ip2long( $ip );
375                         if ( $n < 0 ) {
376                                 $n += pow( 2, 32 );
377                         }
378                 }
379                 return $n;
380         }
381
382         private static function toUnsigned6( $ip ) {
383                 return wfBaseConvert( self::IPv6ToRawHex( $ip ), 16, 10 );
384         }
385
386         /**
387          * Convert a network specification in CIDR notation
388          * to an integer network and a number of bits
389          *
390          * @param $range String: IP with CIDR prefix
391          * @return array(int or string, int)
392          */
393         public static function parseCIDR( $range ) {
394                 if ( self::isIPv6( $range ) ) {
395                         return self::parseCIDR6( $range );
396                 }
397                 $parts = explode( '/', $range, 2 );
398                 if ( count( $parts ) != 2 ) {
399                         return array( false, false );
400                 }
401                 list( $network, $bits ) = $parts;
402                 $network = ip2long( $network );
403                 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
404                         if ( $bits == 0 ) {
405                                 $network = 0;
406                         } else {
407                                 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1);
408                         }
409                         # Convert to unsigned
410                         if ( $network < 0 ) {
411                                 $network += pow( 2, 32 );
412                         }
413                 } else {
414                         $network = false;
415                         $bits = false;
416                 }
417                 return array( $network, $bits );
418         }
419
420         /**
421          * Given a string range in a number of formats,
422          * return the start and end of the range in hexadecimal.
423          *
424          * Formats are:
425          *     1.2.3.4/24          CIDR
426          *     1.2.3.4 - 1.2.3.5   Explicit range
427          *     1.2.3.4             Single IP
428          *
429          *     2001:0db8:85a3::7344/96                                   CIDR
430          *     2001:0db8:85a3::7344 - 2001:0db8:85a3::7344   Explicit range
431          *     2001:0db8:85a3::7344                                      Single IP
432          * @param $range String: IP range
433          * @return array(string, string)
434          */
435         public static function parseRange( $range ) {
436                 // CIDR notation
437                 if ( strpos( $range, '/' ) !== false ) {
438                         if ( self::isIPv6( $range ) ) {
439                                 return self::parseRange6( $range );
440                         }
441                         list( $network, $bits ) = self::parseCIDR( $range );
442                         if ( $network === false ) {
443                                 $start = $end = false;
444                         } else {
445                                 $start = sprintf( '%08X', $network );
446                                 $end = sprintf( '%08X', $network + pow( 2, ( 32 - $bits ) ) - 1 );
447                         }
448                 // Explicit range
449                 } elseif ( strpos( $range, '-' ) !== false ) {
450                         list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
451                         if ( self::isIPv6( $start ) && self::isIPv6( $end ) ) {
452                                 return self::parseRange6( $range );
453                         }
454                         if ( self::isIPv4( $start ) && self::isIPv4( $end ) ) {
455                                 $start = self::toUnsigned( $start );
456                                 $end = self::toUnsigned( $end );
457                                 if ( $start > $end ) {
458                                         $start = $end = false;
459                                 } else {
460                                         $start = sprintf( '%08X', $start );
461                                         $end = sprintf( '%08X', $end );
462                                 }
463                         } else {
464                                 $start = $end = false;
465                         }
466                 } else {
467                         # Single IP
468                         $start = $end = self::toHex( $range );
469                 }
470                 if ( $start === false || $end === false ) {
471                         return array( false, false );
472                 } else {
473                         return array( $start, $end );
474                 }
475         }
476
477         /**
478          * Convert a network specification in IPv6 CIDR notation to an
479          * integer network and a number of bits
480          *
481          * @return array(string, int)
482          */
483         private static function parseCIDR6( $range ) {
484                 # Explode into <expanded IP,range>
485                 $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
486                 if ( count( $parts ) != 2 ) {
487                         return array( false, false );
488                 }
489                 list( $network, $bits ) = $parts;
490                 $network = self::IPv6ToRawHex( $network );
491                 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
492                         if ( $bits == 0 ) {
493                                 $network = "0";
494                         } else {
495                                 # Native 32 bit functions WONT work here!!!
496                                 # Convert to a padded binary number
497                                 $network = wfBaseConvert( $network, 16, 2, 128 );
498                                 # Truncate the last (128-$bits) bits and replace them with zeros
499                                 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
500                                 # Convert back to an integer
501                                 $network = wfBaseConvert( $network, 2, 10 );
502                         }
503                 } else {
504                         $network = false;
505                         $bits = false;
506                 }
507                 return array( $network, (int)$bits );
508         }
509
510         /**
511          * Given a string range in a number of formats, return the
512          * start and end of the range in hexadecimal. For IPv6.
513          *
514          * Formats are:
515          *     2001:0db8:85a3::7344/96                                   CIDR
516          *     2001:0db8:85a3::7344 - 2001:0db8:85a3::7344   Explicit range
517          *     2001:0db8:85a3::7344/96                                   Single IP
518          * @return array(string, string)
519          */
520         private static function parseRange6( $range ) {
521                 # Expand any IPv6 IP
522                 $range = IP::sanitizeIP( $range );
523                 // CIDR notation...
524                 if ( strpos( $range, '/' ) !== false ) {
525                         list( $network, $bits ) = self::parseCIDR6( $range );
526                         if ( $network === false ) {
527                                 $start = $end = false;
528                         } else {
529                                 $start = wfBaseConvert( $network, 10, 16, 32, false );
530                                 # Turn network to binary (again)
531                                 $end = wfBaseConvert( $network, 10, 2, 128 );
532                                 # Truncate the last (128-$bits) bits and replace them with ones
533                                 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
534                                 # Convert to hex
535                                 $end = wfBaseConvert( $end, 2, 16, 32, false );
536                                 # see toHex() comment
537                                 $start = "v6-$start";
538                                 $end = "v6-$end";
539                         }
540                 // Explicit range notation...
541                 } elseif ( strpos( $range, '-' ) !== false ) {
542                         list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
543                         $start = self::toUnsigned6( $start );
544                         $end = self::toUnsigned6( $end );
545                         if ( $start > $end ) {
546                                 $start = $end = false;
547                         } else {
548                                 $start = wfBaseConvert( $start, 10, 16, 32, false );
549                                 $end = wfBaseConvert( $end, 10, 16, 32, false );
550                         }
551                         # see toHex() comment
552                         $start = "v6-$start";
553                         $end = "v6-$end";
554                 } else {
555                         # Single IP
556                         $start = $end = self::toHex( $range );
557                 }
558                 if ( $start === false || $end === false ) {
559                         return array( false, false );
560                 } else {
561                         return array( $start, $end );
562                 }
563         }
564
565         /**
566          * Determine if a given IPv4/IPv6 address is in a given CIDR network
567          *
568          * @param $addr String: the address to check against the given range.
569          * @param $range String: the range to check the given address against.
570          * @return Boolean: whether or not the given address is in the given range.
571          */
572         public static function isInRange( $addr, $range ) {
573                 $hexIP = self::toHex( $addr );
574                 list( $start, $end ) = self::parseRange( $range );
575                 return ( strcmp( $hexIP, $start ) >= 0 &&
576                         strcmp( $hexIP, $end ) <= 0 );
577         }
578
579         /**
580          * Convert some unusual representations of IPv4 addresses to their
581          * canonical dotted quad representation.
582          *
583          * This currently only checks a few IPV4-to-IPv6 related cases.  More
584          * unusual representations may be added later.
585          *
586          * @param $addr String: something that might be an IP address
587          * @return String: valid dotted quad IPv4 address or null
588          */
589         public static function canonicalize( $addr ) {
590                 if ( self::isValid( $addr ) ) {
591                         return $addr;
592                 }
593                 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
594                 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
595                         $addr = substr( $addr, strrpos( $addr, ':' ) + 1 );
596                         if ( self::isIPv4( $addr ) ) {
597                                 return $addr;
598                         }
599                 }
600                 // IPv6 loopback address
601                 $m = array();
602                 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) ) {
603                         return '127.0.0.1';
604                 }
605                 // IPv4-mapped and IPv4-compatible IPv6 addresses
606                 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) ) {
607                         return $m[1];
608                 }
609                 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD .
610                         ':' . RE_IPV6_WORD . '$/i', $addr, $m ) )
611                 {
612                         return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
613                 }
614
615                 return null;  // give up
616         }
617 }