3 * Functions and constants to play with IP addresses and ranges
6 * @author "Ashar Voultoiz" <hashar@altern.org>
7 * @license GPL v2 or later
10 // Some regex definition to "play" with IP address and IP address blocks
12 // An IP is made of 4 bytes from x00 to xFF which is d0 to d255
13 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])');
14 define( 'RE_IP_ADD' , RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
);
15 // An IPv4 block is an IP address and a prefix (d1 to d32)
16 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)');
17 define( 'RE_IP_BLOCK', RE_IP_ADD
. '\/' . RE_IP_PREFIX
);
18 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
19 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
20 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
21 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP
. '(?:ffff:)?' );
22 // An IPv6 block is an IP address and a prefix (d1 to d128)
23 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
24 // An IPv6 IP is made up of 8 octets. However abbreviations like "::" can be used.
25 // This is lax! Number of octets/double colons validation not done.
26 define( 'RE_IPV6_ADD',
28 ':(:' . RE_IPV6_WORD
. '){1,7}' . // IPs that start with ":"
30 RE_IPV6_WORD
. '(:{1,2}' . RE_IPV6_WORD
. '|::$){1,7}' . // IPs that don't start with ":"
33 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD
. '\/' . RE_IPV6_PREFIX
);
34 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
35 define( 'IP_ADDRESS_STRING',
37 RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)' . // IPv4
39 RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)' . // IPv6
44 * A collection of public static functions to play with IP address
49 * Given a string, determine if it as valid IP
50 * Unlike isValid(), this looks for networks too
51 * @param $ip IP address.
54 public static function isIPAddress( $ip ) {
55 if ( !$ip ) return false;
56 if ( is_array( $ip ) ) {
57 throw new MWException( "invalid value passed to " . __METHOD__
);
59 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
60 return preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip) && ( substr_count($ip, '::') < 2 );
63 public static function isIPv6( $ip ) {
64 if ( !$ip ) return false;
65 if( is_array( $ip ) ) {
66 throw new MWException( "invalid value passed to " . __METHOD__
);
68 $doubleColons = substr_count($ip, '::');
69 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
70 return preg_match( '/^' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)$/', $ip)
71 && ( $doubleColons == 1 ||
substr_count($ip,':') == 7 );
74 public static function isIPv4( $ip ) {
75 if ( !$ip ) return false;
76 return preg_match( '/^' . RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)$/', $ip);
80 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
81 * See http://www.answers.com/topic/ipv4-compatible-address
82 * IPs with the first 92 bits as zeros are reserved from IPv6
83 * @param $ip quad-dotted IP address.
86 public static function IPv4toIPv6( $ip ) {
87 if ( !$ip ) return null;
88 // Convert only if needed
89 if ( self
::isIPv6( $ip ) ) return $ip;
91 if ( strpos( $ip, '/' ) !== false ) {
92 $parts = explode( '/', $ip, 2 );
93 if ( count( $parts ) != 2 ) {
96 $network = self
::toUnsigned( $parts[0] );
97 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
98 $bits = $parts[1] +
96;
99 return self
::toOctet( $network ) . "/$bits";
104 return self
::toOctet( self
::toUnsigned( $ip ) );
108 * Given an IPv6 address in octet notation, returns an unsigned integer.
109 * @param $ip octet ipv6 IP address.
112 public static function toUnsigned6( $ip ) {
113 if ( !$ip ) return null;
114 $ip = explode(':', self
::sanitizeIP( $ip ) );
116 foreach ($ip as $v) {
117 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT
);
119 $r_ip = wfBaseConvert( $r_ip, 16, 10 );
124 * Given an IPv6 address in octet notation, returns the expanded octet.
125 * IPv4 IPs will be trimmed, thats it...
126 * @param $ip octet ipv6 IP address.
129 public static function sanitizeIP( $ip ) {
131 if ( $ip === '' ) return null;
132 // Trim and return IPv4 addresses
133 if ( self
::isIPv4($ip) ) return $ip;
134 // Only IPv6 addresses can be expanded
135 if ( !self
::isIPv6($ip) ) return $ip;
136 // Remove any whitespaces, convert to upper case
137 $ip = strtoupper( $ip );
138 // Expand zero abbreviations
139 $abbrevPos = strpos( $ip, '::' );
140 if ( $abbrevPos !== false ) {
141 // If the '::' is at the beginning...
142 if( $abbrevPos == 0 ) {
143 $repeat = '0:'; $extra = ''; $pad = 9; // 7+2 (due to '::')
144 // If the '::' is at the end...
145 } else if( $abbrevPos == (strlen($ip)-2) ) {
146 $repeat = ':0'; $extra = ''; $pad = 9; // 7+2 (due to '::')
147 // If the '::' is at the end...
149 $repeat = ':0'; $extra = ':'; $pad = 8; // 6+2 (due to '::')
151 $ip = str_replace('::', str_repeat($repeat, $pad-substr_count($ip,':')).$extra, $ip);
153 // Remove leading zereos from each bloc as needed
154 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip );
159 * Given an unsigned integer, returns an IPv6 address in octet notation
160 * @param $ip_int integer IP address.
163 public static function toOctet( $ip_int ) {
164 // Convert to padded uppercase hex
165 $ip_hex = wfBaseConvert($ip_int, 10, 16, 32, false);
166 // Separate into 8 octets
167 $ip_oct = substr( $ip_hex, 0, 4 );
168 for ($n=1; $n < 8; $n++
) {
169 $ip_oct .= ':' . substr($ip_hex, 4*$n, 4);
172 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip_oct );
177 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
179 public static function formatHex( $hex ) {
180 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
181 return self
::hexToOctet( $hex );
183 return self
::hexToQuad( $hex );
188 * Given a hexadecimal number, returns to an IPv6 address in octet notation
189 * @param $ip_hex string hex IP
192 public static function hextoOctet( $ip_hex ) {
193 // Convert to padded uppercase hex
194 $ip_hex = str_pad( strtoupper($ip_hex), 32, '0');
195 // Separate into 8 octets
196 $ip_oct = substr( $ip_hex, 0, 4 );
197 for ($n=1; $n < 8; $n++
) {
198 $ip_oct .= ':' . substr($ip_hex, 4*$n, 4);
201 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip_oct );
206 * Converts a hexadecimal number to an IPv4 address in octet notation
207 * @param $ip string Hex IP
210 public static function hexToQuad( $ip ) {
211 // Converts a hexadecimal IP to nnn.nnn.nnn.nnn format
213 for ( $i = 0; $i < 4; $i++
) {
217 $s .= base_convert( substr( $ip, $i * 2, 2 ), 16, 10 );
223 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
224 * @return array(string, int)
226 public static function parseCIDR6( $range ) {
228 $parts = explode( '/', IP
::sanitizeIP( $range ), 2 );
229 if ( count( $parts ) != 2 ) {
230 return array( false, false );
232 $network = self
::toUnsigned6( $parts[0] );
233 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
238 # Native 32 bit functions WONT work here!!!
239 # Convert to a padded binary number
240 $network = wfBaseConvert( $network, 10, 2, 128 );
241 # Truncate the last (128-$bits) bits and replace them with zeros
242 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
243 # Convert back to an integer
244 $network = wfBaseConvert( $network, 2, 10 );
250 return array( $network, $bits );
254 * Given a string range in a number of formats, return the start and end of
255 * the range in hexadecimal. For IPv6.
258 * 2001:0db8:85a3::7344/96 CIDR
259 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
260 * 2001:0db8:85a3::7344/96 Single IP
261 * @return array(string, int)
263 public static function parseRange6( $range ) {
265 $range = IP
::sanitizeIP( $range );
266 if ( strpos( $range, '/' ) !== false ) {
268 list( $network, $bits ) = self
::parseCIDR6( $range );
269 if ( $network === false ) {
270 $start = $end = false;
272 $start = wfBaseConvert( $network, 10, 16, 32, false );
273 # Turn network to binary (again)
274 $end = wfBaseConvert( $network, 10, 2, 128 );
275 # Truncate the last (128-$bits) bits and replace them with ones
276 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT
);
278 $end = wfBaseConvert( $end, 2, 16, 32, false );
279 # see toHex() comment
280 $start = "v6-$start"; $end = "v6-$end";
282 } elseif ( strpos( $range, '-' ) !== false ) {
284 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
285 $start = self
::toUnsigned6( $start ); $end = self
::toUnsigned6( $end );
286 if ( $start > $end ) {
287 $start = $end = false;
289 $start = wfBaseConvert( $start, 10, 16, 32, false );
290 $end = wfBaseConvert( $end, 10, 16, 32, false );
292 # see toHex() comment
293 $start = "v6-$start"; $end = "v6-$end";
296 $start = $end = self
::toHex( $range );
298 if ( $start === false ||
$end === false ) {
299 return array( false, false );
301 return array( $start, $end );
306 * Validate an IP address.
307 * @return boolean True if it is valid.
309 public static function isValid( $ip ) {
310 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip) );
314 * Validate an IP Block.
315 * @return boolean True if it is valid.
317 public static function isValidBlock( $ipblock ) {
318 return ( count(self
::toArray($ipblock)) == 1 +
5 );
322 * Determine if an IP address really is an IP address, and if it is public,
323 * i.e. not RFC 1918 or similar
324 * Comes from ProxyTools.php
326 public static function isPublic( $ip ) {
327 $n = self
::toUnsigned( $ip );
332 // ip2long accepts incomplete addresses, as well as some addresses
333 // followed by garbage characters. Check that it's really valid.
334 if( $ip != long2ip( $n ) ) {
338 static $privateRanges = false;
339 if ( !$privateRanges ) {
340 $privateRanges = array(
341 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
342 array( '172.16.0.0', '172.31.255.255' ), # "
343 array( '192.168.0.0', '192.168.255.255' ), # "
344 array( '0.0.0.0', '0.255.255.255' ), # this network
345 array( '127.0.0.0', '127.255.255.255' ), # loopback
349 foreach ( $privateRanges as $r ) {
350 $start = self
::toUnsigned( $r[0] );
351 $end = self
::toUnsigned( $r[1] );
352 if ( $n >= $start && $n <= $end ) {
360 * Split out an IP block as an array of 4 bytes and a mask,
361 * return false if it can't be determined
363 * @param $ipblock string A quad dotted/octet IP address
366 public static function toArray( $ipblock ) {
368 if( preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:'.RE_IP_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
370 } else if ( preg_match( '/^' . RE_IPV6_ADD
. '(?:\/(?:'.RE_IPV6_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
378 * Return a zero-padded hexadecimal representation of an IP address.
380 * Hexadecimal addresses are used because they can easily be extended to
381 * IPv6 support. To separate the ranges, the return value from this
382 * function for an IPv6 address will be prefixed with "v6-", a non-
383 * hexadecimal string which sorts after the IPv4 addresses.
385 * @param $ip Quad dotted/octet IP address.
386 * @return hexidecimal
388 public static function toHex( $ip ) {
389 $n = self
::toUnsigned( $ip );
390 if ( $n !== false ) {
391 $n = self
::isIPv6($ip) ?
"v6-" . wfBaseConvert( $n, 10, 16, 32, false ) : wfBaseConvert( $n, 10, 16, 8, false );
397 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
398 * Like ip2long() except that it actually works and has a consistent error return value.
399 * Comes from ProxyTools.php
400 * @param $ip Quad dotted IP address.
403 public static function toUnsigned( $ip ) {
404 // Use IPv6 functions if needed
405 if ( self
::isIPv6( $ip ) ) {
406 return self
::toUnsigned6( $ip );
408 if ( $ip == '255.255.255.255' ) {
412 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
423 * Convert a dotted-quad IP to a signed integer
424 * Returns false on failure
426 public static function toSigned( $ip ) {
427 if ( $ip == '255.255.255.255' ) {
439 * Convert a network specification in CIDR notation to an integer network and a number of bits
440 * @return array(string, int)
442 public static function parseCIDR( $range ) {
443 $parts = explode( '/', $range, 2 );
444 if ( count( $parts ) != 2 ) {
445 return array( false, false );
447 $network = self
::toSigned( $parts[0] );
448 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
453 $network &= ~
((1 << (32 - $bits)) - 1);
455 # Convert to unsigned
456 if ( $network < 0 ) {
457 $network +
= pow( 2, 32 );
463 return array( $network, $bits );
467 * Given a string range in a number of formats, return the start and end of
468 * the range in hexadecimal.
472 * 1.2.3.4 - 1.2.3.5 Explicit range
475 * 2001:0db8:85a3::7344/96 CIDR
476 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
477 * 2001:0db8:85a3::7344 Single IP
478 * @return array(string, int)
480 public static function parseRange( $range ) {
481 // Use IPv6 functions if needed
482 if ( self
::isIPv6( $range ) ) {
483 return self
::parseRange6( $range );
485 if ( strpos( $range, '/' ) !== false ) {
487 list( $network, $bits ) = self
::parseCIDR( $range );
488 if ( $network === false ) {
489 $start = $end = false;
491 $start = sprintf( '%08X', $network );
492 $end = sprintf( '%08X', $network +
pow( 2, (32 - $bits) ) - 1 );
494 } elseif ( strpos( $range, '-' ) !== false ) {
496 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
497 if( self
::isIPAddress( $start ) && self
::isIPAddress( $end ) ) {
498 $start = self
::toUnsigned( $start ); $end = self
::toUnsigned( $end );
499 if ( $start > $end ) {
500 $start = $end = false;
502 $start = sprintf( '%08X', $start );
503 $end = sprintf( '%08X', $end );
506 $start = $end = false;
510 $start = $end = self
::toHex( $range );
512 if ( $start === false ||
$end === false ) {
513 return array( false, false );
515 return array( $start, $end );
520 * Determine if a given IPv4/IPv6 address is in a given CIDR network
521 * @param $addr The address to check against the given range.
522 * @param $range The range to check the given address against.
523 * @return bool Whether or not the given address is in the given range.
525 public static function isInRange( $addr, $range ) {
526 // Convert to IPv6 if needed
527 $hexIP = self
::toHex( $addr );
528 list( $start, $end ) = self
::parseRange( $range );
529 return (strcmp($hexIP, $start) >= 0 &&
530 strcmp($hexIP, $end) <= 0);
534 * Convert some unusual representations of IPv4 addresses to their
535 * canonical dotted quad representation.
537 * This currently only checks a few IPV4-to-IPv6 related cases. More
538 * unusual representations may be added later.
540 * @param $addr something that might be an IP address
541 * @return valid dotted quad IPv4 address or null
543 public static function canonicalize( $addr ) {
544 if ( self
::isValid( $addr ) )
547 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
548 if ( strpos($addr,':') !==false && strpos($addr,'.') !==false ) {
549 $addr = substr( $addr, strrpos($addr,':')+
1 );
550 if( self
::isIPv4($addr) ) return $addr;
553 // IPv6 loopback address
555 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) )
558 // IPv4-mapped and IPv4-compatible IPv6 addresses
559 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) )
561 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
562 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
564 return null; // give up