9567f1effac7e6e6b2bd9878b06856c410f63e2d
3 * Collection of public static functions to play with IP address
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. This is lax!
25 define( 'RE_IPV6_ADD', '(:(:' . RE_IPV6_WORD
. '){1,7}|' . RE_IPV6_WORD
. '(:{1,2}' . RE_IPV6_WORD
. '|::$){1,7})' );
26 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD
. '\/' . RE_IPV6_PREFIX
);
27 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
28 define( 'IP_ADDRESS_STRING', RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)|' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)');
32 * Given a string, determine if it as valid IP
33 * Unlike isValid(), this looks for networks too
34 * @param $ip IP address.
37 public static function isIPAddress( $ip ) {
38 if ( !$ip ) return false;
39 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
40 return preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip) && ( substr_count($ip, '::') < 2 );
43 public static function isIPv6( $ip ) {
44 if ( !$ip ) return false;
45 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
46 return preg_match( '/^' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)$/', $ip) && ( substr_count($ip, '::') < 2);
49 public static function isIPv4( $ip ) {
50 if ( !$ip ) return false;
51 return preg_match( '/^' . RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)$/', $ip);
55 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
56 * See http://www.answers.com/topic/ipv4-compatible-address
57 * IPs with the first 92 bits as zeros are reserved from IPv6
58 * @param $ip quad-dotted IP address.
61 public static function IPv4toIPv6( $ip ) {
62 if ( !$ip ) return null;
63 // Convert only if needed
64 if ( self
::isIPv6( $ip ) ) return $ip;
66 if ( strpos( $ip, '/' ) !== false ) {
67 $parts = explode( '/', $ip, 2 );
68 if ( count( $parts ) != 2 ) {
71 $network = self
::toUnsigned( $parts[0] );
72 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
73 $bits = $parts[1] +
96;
74 return self
::toOctet( $network ) . "/$bits";
79 return self
::toOctet( self
::toUnsigned( $ip ) );
83 * Given an IPv6 address in octet notation, returns an unsigned integer.
84 * @param $ip octet ipv6 IP address.
87 public static function toUnsigned6( $ip ) {
88 if ( !$ip ) return null;
89 $ip = explode(':', self
::sanitizeIP( $ip ) );
92 $r_ip .= wfBaseConvert( $v, 16, 2, 16);
94 return wfBaseConvert($r_ip, 2, 10);
98 * Given an IPv6 address in octet notation, returns the expanded octet.
99 * @param $ip octet ipv6 IP address.
102 public static function sanitizeIP( $ip ) {
103 if ( !$ip ) return null;
104 // Trim and return IPv4 addresses
105 if ( self
::isIPv4($ip) ) return trim($ip);
106 // Only IPv6 addresses can be expanded
107 if ( !self
::isIPv6($ip) ) return $ip;
108 // Remove any whitespaces, convert to upper case
109 $ip = strtoupper( trim($ip) );
110 // Expand zero abbreviations
111 if ( substr_count($ip, '::') ) {
112 $ip = str_replace('::', str_repeat(':0', 8 - substr_count($ip, ':')) . ':', $ip);
114 // For IPs that start with "::", correct the final IP so that it starts with '0' and not ':'
115 if ( strpos( $ip, ':' ) === 0 ) $ip = "0$ip";
116 // Remove leading zereos from each bloc as needed
117 $ip = explode( ':', $ip );
118 for ( $n=0; $n < count($ip); $n++
) {
119 $ip[$n] = preg_replace( '/^0+' . RE_IPV6_WORD
. '/', '$1', $ip[$n] );
121 $ip = implode( ':', $ip );
126 * Given an unsigned integer, returns an IPv6 address in octet notation
127 * @param $ip integer IP address.
130 public static function toOctet( $ip_int ) {
131 // Convert integer to binary
132 $ip_int = wfBaseConvert($ip_int, 10, 2, 128);
133 // Seperate into 8 octets
134 $ip_oct = wfBaseConvert( substr( $ip_int, 0, 16 ), 2, 16, 1, false );
135 for ($n=1; $n < 8; $n++
) {
136 // Convert to uppercase hex, and add ":" marks, with NO leading zeroes
137 $ip_oct .= ':' . wfBaseConvert( substr($ip_int, 16*$n, 16), 2, 16, 1, false );
143 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
144 * @return array(string, int)
146 public static function parseCIDR6( $range ) {
148 $parts = explode( '/', IP
::sanitizeIP( $range ), 2 );
149 if ( count( $parts ) != 2 ) {
150 return array( false, false );
152 $network = self
::toUnsigned6( $parts[0] );
153 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
158 # Native 32 bit functions WONT work here!!!
159 # Convert to a padded binary number
160 $network = wfBaseConvert( $network, 10, 2, 128 );
161 # Truncate the last (128-$bits) bits and replace them with zeros
162 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
163 # Convert back to an integer
164 $network = wfBaseConvert( $network, 2, 10 );
171 return array( $network, $bits );
175 * Given a string range in a number of formats, return the start and end of
176 * the range in hexadecimal. For IPv6.
179 * 2001:0db8:85a3::7344/96 CIDR
180 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
181 * 2001:0db8:85a3::7344/96 Single IP
182 * @return array(string, int)
184 public static function parseRange6( $range ) {
186 $range = IP
::sanitizeIP( $range );
187 if ( strpos( $range, '/' ) !== false ) {
189 list( $network, $bits ) = self
::parseCIDR6( $range );
190 if ( $network === false ) {
191 $start = $end = false;
193 $start = wfBaseConvert( $network, 10, 16, 32, false );
194 # Turn network to binary (again)
195 $end = wfBaseConvert( $network, 10, 2, 128 );
196 # Truncate the last (128-$bits) bits and replace them with ones
197 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT
);
199 $end = wfBaseConvert( $end, 2, 16, 32, false );
201 } elseif ( strpos( $range, '-' ) !== false ) {
203 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
204 $start = self
::toUnsigned6( $start ); $end = self
::toUnsigned6( $end );
205 if ( $start > $end ) {
206 $start = $end = false;
208 $start = wfBaseConvert( $start, 10, 16, 32, false );
209 $end = wfBaseConvert( $end, 10, 16, 32, false );
213 $start = $end = self
::toHex( $range );
215 if ( $start === false ||
$end === false ) {
216 return array( false, false );
218 return array( $start, $end );
223 * Validate an IP address.
224 * @return boolean True if it is valid.
226 public static function isValid( $ip ) {
227 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip) );
231 * Validate an IP Block.
232 * @return boolean True if it is valid.
234 public static function isValidBlock( $ipblock ) {
235 return ( count(self
::toArray($ipblock)) == 1 +
5 );
239 * Determine if an IP address really is an IP address, and if it is public,
240 * i.e. not RFC 1918 or similar
241 * Comes from ProxyTools.php
243 public static function isPublic( $ip ) {
244 $n = self
::toUnsigned( $ip );
249 // ip2long accepts incomplete addresses, as well as some addresses
250 // followed by garbage characters. Check that it's really valid.
251 if( $ip != long2ip( $n ) ) {
255 static $privateRanges = false;
256 if ( !$privateRanges ) {
257 $privateRanges = array(
258 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
259 array( '172.16.0.0', '172.31.255.255' ), # "
260 array( '192.168.0.0', '192.168.255.255' ), # "
261 array( '0.0.0.0', '0.255.255.255' ), # this network
262 array( '127.0.0.0', '127.255.255.255' ), # loopback
266 foreach ( $privateRanges as $r ) {
267 $start = self
::toUnsigned( $r[0] );
268 $end = self
::toUnsigned( $r[1] );
269 if ( $n >= $start && $n <= $end ) {
277 * Split out an IP block as an array of 4 bytes and a mask,
278 * return false if it can't be determined
280 * @parameter $ip string A quad dotted/octet IP address
283 public static function toArray( $ipblock ) {
285 if( preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:'.RE_IP_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
287 } else if ( preg_match( '/^' . RE_IPV6_ADD
. '(?:\/(?:'.RE_IPV6_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
295 * Return a zero-padded hexadecimal representation of an IP address.
297 * Hexadecimal addresses are used because they can easily be extended to
298 * IPv6 support. To separate the ranges, the return value from this
299 * function for an IPv6 address will be prefixed with "v6-", a non-
300 * hexadecimal string which sorts after the IPv4 addresses.
302 * @param $ip Quad dotted/octet IP address.
303 * @return hexidecimal
305 public static function toHex( $ip ) {
306 $n = self
::toUnsigned( $ip );
307 if ( $n !== false ) {
308 $n = ( self
::isIPv6($ip) ) ?
wfBaseConvert( $n, 10, 16, 32, false ) : wfBaseConvert( $n, 10, 16, 8, false );
314 * Given an IP address in dotted-quad notation, returns an unsigned integer.
315 * Like ip2long() except that it actually works and has a consistent error return value.
316 * Comes from ProxyTools.php
317 * @param $ip Quad dotted IP address.
320 public static function toUnsigned( $ip ) {
321 // Use IPv6 functions if needed
322 if ( self
::isIPv6( $ip ) ) {
323 return self
::toUnsigned6( $ip );
325 if ( $ip == '255.255.255.255' ) {
329 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
340 * Convert a dotted-quad IP to a signed integer
341 * Returns false on failure
343 public static function toSigned( $ip ) {
344 if ( $ip == '255.255.255.255' ) {
356 * Convert a network specification in CIDR notation to an integer network and a number of bits
357 * @return array(string, int)
359 public static function parseCIDR( $range ) {
360 $parts = explode( '/', $range, 2 );
361 if ( count( $parts ) != 2 ) {
362 return array( false, false );
364 $network = self
::toSigned( $parts[0] );
365 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
370 $network &= ~
((1 << (32 - $bits)) - 1);
372 # Convert to unsigned
373 if ( $network < 0 ) {
374 $network +
= pow( 2, 32 );
380 return array( $network, $bits );
384 * Given a string range in a number of formats, return the start and end of
385 * the range in hexadecimal. For IPv4.
389 * 1.2.3.4 - 1.2.3.5 Explicit range
391 * @return array(string, int)
393 public static function parseRange( $range ) {
394 // Use IPv6 functions if needed
395 if ( self
::isIPv6( $range ) ) {
396 return self
::parseRange6( $range );
398 if ( strpos( $range, '/' ) !== false ) {
400 list( $network, $bits ) = self
::parseCIDR( $range );
401 if ( $network === false ) {
402 $start = $end = false;
404 $start = sprintf( '%08X', $network );
405 $end = sprintf( '%08X', $network +
pow( 2, (32 - $bits) ) - 1 );
407 } elseif ( strpos( $range, '-' ) !== false ) {
409 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
410 $start = self
::toUnsigned( $start ); $end = self
::toUnsigned( $end );
411 if ( $start > $end ) {
412 $start = $end = false;
414 $start = sprintf( '%08X', $start );
415 $end = sprintf( '%08X', $end );
419 $start = $end = self
::toHex( $range );
421 if ( $start === false ||
$end === false ) {
422 return array( false, false );
424 return array( $start, $end );
429 * Determine if a given IPv4/IPv6 address is in a given CIDR network
430 * @param $addr The address to check against the given range.
431 * @param $range The range to check the given address against.
432 * @return bool Whether or not the given address is in the given range.
434 public static function isInRange( $addr, $range ) {
435 // Convert to IPv6 if needed
436 $unsignedIP = self
::toUnsigned( $addr );
437 list( $start, $end ) = self
::parseRange($range );
438 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
442 * Convert some unusual representations of IPv4 addresses to their
443 * canonical dotted quad representation.
445 * This currently only checks a few IPV4-to-IPv6 related cases. More
446 * unusual representations may be added later.
448 * @param $addr something that might be an IP address
449 * @return valid dotted quad IPv4 address or null
451 public static function canonicalize( $addr ) {
452 if ( self
::isValid( $addr ) )
455 // IPv6 loopback address
457 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) )
460 // IPv4-mapped and IPv4-compatible IPv6 addresses
461 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) )
463 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
464 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
466 return null; // give up