9a1d7bf0240804e72bfbe2a33dcb6d9381b6f996
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 function isIPAddress( $ip ) {
38 if ( !$ip ) return false;
39 return preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip);
42 public function isIPv6( $ip ) {
43 return preg_match( '/^' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)$/', $ip);
46 public function isIPv4( $ip ) {
47 return preg_match( '/^' . RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)$/', $ip);
51 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
52 * See http://www.answers.com/topic/ipv4-compatible-address
53 * IPs with the first 92 bits as zeros are reserved from IPv6
54 * @param $ip quad-dotted IP address.
57 public function IPv4toIPv6( $ip ) {
58 if ( !$ip ) return null;
59 // Convert only if needed
60 if ( self
::isIPv6( $ip ) ) return $ip;
62 if ( strpos( $ip, '/' ) !== false ) {
63 $parts = explode( '/', $ip, 2 );
64 if ( count( $parts ) != 2 ) {
67 $network = self
::toUnsigned( $parts[0] );
68 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
69 $bits = $parts[1] +
96;
70 return self
::toOctet( $network ) . "/$bits";
75 return self
::toOctet( self
::toUnsigned( $ip ) );
79 * Given an IPv6 address in octet notation, returns an unsigned integer.
80 * @param $ip octet ipv6 IP address.
83 public function toUnsigned6( $ip ) {
84 if ( !$ip ) return null;
85 $ip = explode(':', self
::sanitizeIP( $ip ) );
88 $r_ip .= wfBaseConvert( $v, 16, 2, 16);
90 return wfBaseConvert($r_ip, 2, 10);
94 * Given an IPv6 address in octet notation, returns the expanded octet.
95 * @param $ip octet ipv6 IP address.
98 public function sanitizeIP( $ip ) {
99 if ( !$ip ) return null;
100 // Only IPv6 addresses can be expanded
101 if ( !self
::isIPv6( $ip ) ) return $ip;
102 // Convert to upper case
103 $ip = strtoupper( $ip );
104 // Expand zero abbreviations
105 if ( substr_count($ip, '::') ) {
106 $ip = str_replace('::', str_repeat(':0000', 8 - substr_count($ip, ':')) . ':', $ip);
112 * Given an unsigned integer, returns an IPv6 address in octet notation
113 * @param $ip integer IP address.
116 public function toOctet( $ip_int ) {
117 // Convert integer to binary
118 $ip_int = wfBaseConvert($ip_int, 10, 2, 128);
119 // Seperate into 8 octets
120 $ip_oct = wfBaseConvert( substr( $ip_int, 0, 16 ), 2, 16, 1, false );
121 for ($n=1; $n < 8; $n++
) {
122 // Convert to hex, and add ":" marks
123 $ip_oct .= ':' . wfBaseConvert( substr($ip_int, 16*$n, 16), 2, 16, 1, false );
129 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
130 * @return array(string, int)
132 public static function parseCIDR6( $range ) {
134 $parts = explode( '/', IP
::sanitizeIP( $range ), 2 );
135 if ( count( $parts ) != 2 ) {
136 return array( false, false );
138 $network = self
::toUnsigned6( $parts[0] );
139 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
144 # Native 32 bit functions WONT work here!!!
145 # Convert to a padded binary number
146 $network = wfBaseConvert( $network, 10, 2, 128 );
147 # Truncate the last (128-$bits) bits and replace them with zeros
148 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
149 # Convert back to an integer
150 $network = wfBaseConvert( $network, 2, 10 );
157 return array( $network, $bits );
161 * Given a string range in a number of formats, return the start and end of
162 * the range in hexadecimal. For IPv6.
165 * 2001:0db8:85a3::7344/96 CIDR
166 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
167 * 2001:0db8:85a3::7344/96 Single IP
168 * @return array(string, int)
170 public static function parseRange6( $range ) {
172 $range = IP
::sanitizeIP( $range );
173 if ( strpos( $range, '/' ) !== false ) {
175 list( $network, $bits ) = self
::parseCIDR6( $range );
176 if ( $network === false ) {
177 $start = $end = false;
179 $start = wfBaseConvert( $network, 10, 16, 1, false );
180 # Turn network to binary (again)
181 $end = wfBaseConvert( $network, 10, 2, 128 );
182 # Truncate the last (128-$bits) bits and replace them with ones
183 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT
);
185 $end = wfBaseConvert( $end, 2, 16, 1, false );
187 } elseif ( strpos( $range, '-' ) !== false ) {
189 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
190 $start = self
::toUnsigned6( $start ); $end = self
::toUnsigned6( $end );
191 if ( $start > $end ) {
192 $start = $end = false;
194 $start = wfBaseConvert( $start, 10, 16, 1, false );
195 $end = wfBaseConvert( $end, 10, 16, 1, false );
199 $start = $end = self
::toHex( $range );
201 if ( $start === false ||
$end === false ) {
202 return array( false, false );
204 return array( $start, $end );
209 * Validate an IP address.
210 * @return boolean True if it is valid.
212 public static function isValid( $ip ) {
213 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip) );
217 * Validate an IP Block.
218 * @return boolean True if it is valid.
220 public static function isValidBlock( $ipblock ) {
221 return ( count(self
::toArray($ipblock)) == 1 +
5 );
225 * Determine if an IP address really is an IP address, and if it is public,
226 * i.e. not RFC 1918 or similar
227 * Comes from ProxyTools.php
229 public static function isPublic( $ip ) {
230 $n = self
::toUnsigned( $ip );
235 // ip2long accepts incomplete addresses, as well as some addresses
236 // followed by garbage characters. Check that it's really valid.
237 if( $ip != long2ip( $n ) ) {
241 static $privateRanges = false;
242 if ( !$privateRanges ) {
243 $privateRanges = array(
244 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
245 array( '172.16.0.0', '172.31.255.255' ), # "
246 array( '192.168.0.0', '192.168.255.255' ), # "
247 array( '0.0.0.0', '0.255.255.255' ), # this network
248 array( '127.0.0.0', '127.255.255.255' ), # loopback
252 foreach ( $privateRanges as $r ) {
253 $start = self
::toUnsigned( $r[0] );
254 $end = self
::toUnsigned( $r[1] );
255 if ( $n >= $start && $n <= $end ) {
263 * Split out an IP block as an array of 4 bytes and a mask,
264 * return false if it can't be determined
266 * @parameter $ip string A quad dotted/octet IP address
269 public static function toArray( $ipblock ) {
271 if( preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:'.RE_IP_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
273 } else if ( preg_match( '/^' . RE_IPV6_ADD
. '(?:\/(?:'.RE_IPV6_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
281 * Return a zero-padded hexadecimal representation of an IP address.
283 * Hexadecimal addresses are used because they can easily be extended to
284 * IPv6 support. To separate the ranges, the return value from this
285 * function for an IPv6 address will be prefixed with "v6-", a non-
286 * hexadecimal string which sorts after the IPv4 addresses.
288 * @param $ip Quad dotted IP address.
289 * @return hexidecimal
291 public static function toHex( $ip ) {
292 // Use IPv6 functions if needed
293 $n = ( self
::isIPv6($ip) ) ? self
::toUnsigned6( $ip ) : self
::toUnsigned( $ip );
294 if ( $n !== false ) {
295 $n = wfBaseConvert( $n, 10, 16, 1, false );
301 * Given an IP address in dotted-quad notation, returns an unsigned integer.
302 * Like ip2long() except that it actually works and has a consistent error return value.
303 * Comes from ProxyTools.php
304 * @param $ip Quad dotted IP address.
307 public static function toUnsigned( $ip ) {
308 // Use IPv6 functions if needed
309 if ( self
::isIPv6( $ip ) ) {
310 return toUnsigned6( $ip );
312 if ( $ip == '255.255.255.255' ) {
316 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
327 * Convert a dotted-quad IP to a signed integer
328 * Returns false on failure
330 public static function toSigned( $ip ) {
331 if ( $ip == '255.255.255.255' ) {
343 * Convert a network specification in CIDR notation to an integer network and a number of bits
344 * @return array(string, int)
346 public static function parseCIDR( $range ) {
347 $parts = explode( '/', $range, 2 );
348 if ( count( $parts ) != 2 ) {
349 return array( false, false );
351 $network = self
::toSigned( $parts[0] );
352 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
357 $network &= ~
((1 << (32 - $bits)) - 1);
359 # Convert to unsigned
360 if ( $network < 0 ) {
361 $network +
= pow( 2, 32 );
367 return array( $network, $bits );
371 * Given a string range in a number of formats, return the start and end of
372 * the range in hexadecimal. For IPv4.
376 * 1.2.3.4 - 1.2.3.5 Explicit range
378 * @return array(string, int)
380 public static function parseRange( $range ) {
381 // Use IPv6 functions if needed
382 if ( self
::isIPv6( $range ) ) {
383 return self
::parseRange6( $range );
385 if ( strpos( $range, '/' ) !== false ) {
387 list( $network, $bits ) = self
::parseCIDR( $range );
388 if ( $network === false ) {
389 $start = $end = false;
391 $start = sprintf( '%08X', $network );
392 $end = sprintf( '%08X', $network +
pow( 2, (32 - $bits) ) - 1 );
394 } elseif ( strpos( $range, '-' ) !== false ) {
396 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
397 $start = self
::toUnsigned( $start ); $end = self
::toUnsigned( $end );
398 if ( $start > $end ) {
399 $start = $end = false;
401 $start = sprintf( '%08X', $start );
402 $end = sprintf( '%08X', $end );
406 $start = $end = self
::toHex( $range );
408 if ( $start === false ||
$end === false ) {
409 return array( false, false );
411 return array( $start, $end );
416 * Determine if a given IPv4 address is in a given CIDR network
417 * @param $addr The address to check against the given range.
418 * @param $range The range to check the given address against.
419 * @return bool Whether or not the given address is in the given range.
421 public static function isInRange( $addr, $range ) {
422 // Convert to IPv6 if needed
423 $unsignedIP = self
::toUnsigned6( self
::IPv4toIPv6($addr) );
424 list( $start, $end ) = self
::parseRange6( self
::IPv4toIPv6($range) );
425 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
429 * Convert some unusual representations of IPv4 addresses to their
430 * canonical dotted quad representation.
432 * This currently only checks a few IPV4-to-IPv6 related cases. More
433 * unusual representations may be added later.
435 * @param $addr something that might be an IP address
436 * @return valid dotted quad IPv4 address or null
438 public static function canonicalize( $addr ) {
439 if ( self
::isValid( $addr ) )
442 // IPv6 loopback address
444 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) )
447 // IPv4-mapped and IPv4-compatible IPv6 addresses
448 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) )
450 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
451 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
453 return null; // give up