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,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 $bits = $parts[1] +
96;
69 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
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
::expandIP( $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 expandIP( $ip ) {
99 if ( !$ip ) return null;
100 // Only IPv6 addresses can be expanded
101 if ( !self
::isIPv6( $ip ) ) return $ip;
102 // Expand zero abbreviations
103 if ( substr_count($ip, '::') ) {
104 $ip = str_replace('::', str_repeat(':0000', 8 - substr_count($ip, ':')) . ':', $ip);
110 * Given an unsigned integer, returns an IPv6 address in octet notation
111 * @param $ip integer ipv6 IP address.
114 public function toOctet( $ip_int ) {
115 // Convert integer to binary
116 $ip_int = wfBaseConvert($ip_int, 10, 2, 128);
117 // Seperate into 8 octets
118 $ip_oct = base_convert( substr( $ip_int, 0, 16 ), 2, 16 );
119 for ($n=1; $n < 8; $n++
) {
120 // Convert to hex, and add ":" marks
121 $ip_oct .= ':' . base_convert( substr($ip_int, 16*$n, 16), 2, 16 );
127 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
128 * @return array(string, int)
130 public static function parseCIDR6( $range ) {
131 $parts = explode( '/', $range, 2 );
132 if ( count( $parts ) != 2 ) {
133 return array( false, false );
135 $network = self
::toUnsigned6( $parts[0] );
136 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
141 # Native 32 bit functions WONT work here!!!
142 # Convert to a padded binary number
143 $network = wfBaseConvert( $network, 10, 2, 128 );
144 # Truncate the last (128-$bits) bits and replace them with zeros
145 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
146 # Convert back to an integer
147 $network = wfBaseConvert( $network, 2, 10 );
154 return array( $network, $bits );
158 * Given a string range in a number of formats, return the start and end of
159 * the range in hexadecimal. For IPv6.
162 * 2001:0db8:85a3::7344/96 CIDR
163 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
164 * 2001:0db8:85a3::7344/96 Single IP
165 * @return array(string, int)
167 public static function parseRange6( $range ) {
168 if ( strpos( $range, '/' ) !== false ) {
170 list( $network, $bits ) = self
::parseCIDR6( $range );
171 if ( $network === false ) {
172 $start = $end = false;
174 $start = sprintf( '%08X', $network );
175 $end = sprintf( '%08X', $network +
pow( 2, (128 - $bits) ) - 1 );
177 } elseif ( strpos( $range, '-' ) !== false ) {
179 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
180 $start = self
::toUnsigned6( $start ); $end = self
::toUnsigned6( $end );
181 if ( $start > $end ) {
182 $start = $end = false;
184 $start = sprintf( '%08X', $start );
185 $end = sprintf( '%08X', $end );
189 $start = $end = self
::toHex( $range );
191 if ( $start === false ||
$end === false ) {
192 return array( false, false );
194 return array( $start, $end );
199 * Validate an IP address.
200 * @return boolean True if it is valid.
202 public static function isValid( $ip ) {
203 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip) );
207 * Validate an IP Block.
208 * @return boolean True if it is valid.
210 public static function isValidBlock( $ipblock ) {
211 return ( count(self
::toArray($ipblock)) == 1 +
5 );
215 * Determine if an IP address really is an IP address, and if it is public,
216 * i.e. not RFC 1918 or similar
217 * Comes from ProxyTools.php
219 public static function isPublic( $ip ) {
220 $n = self
::toUnsigned( $ip );
225 // ip2long accepts incomplete addresses, as well as some addresses
226 // followed by garbage characters. Check that it's really valid.
227 if( $ip != long2ip( $n ) ) {
231 static $privateRanges = false;
232 if ( !$privateRanges ) {
233 $privateRanges = array(
234 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
235 array( '172.16.0.0', '172.31.255.255' ), # "
236 array( '192.168.0.0', '192.168.255.255' ), # "
237 array( '0.0.0.0', '0.255.255.255' ), # this network
238 array( '127.0.0.0', '127.255.255.255' ), # loopback
242 foreach ( $privateRanges as $r ) {
243 $start = self
::toUnsigned( $r[0] );
244 $end = self
::toUnsigned( $r[1] );
245 if ( $n >= $start && $n <= $end ) {
253 * Split out an IP block as an array of 4 bytes and a mask,
254 * return false if it can't be determined
256 * @parameter $ip string A quad dotted IP address
259 public static function toArray( $ipblock ) {
261 if(! preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:'.RE_IP_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
269 * Return a zero-padded hexadecimal representation of an IP address.
271 * Hexadecimal addresses are used because they can easily be extended to
272 * IPv6 support. To separate the ranges, the return value from this
273 * function for an IPv6 address will be prefixed with "v6-", a non-
274 * hexadecimal string which sorts after the IPv4 addresses.
276 * @param $ip Quad dotted IP address.
277 * @return hexidecimal
279 public static function toHex( $ip ) {
280 // Use IPv6 function if we have an that sort of IP
281 $n = ( self
::isIPv6($ip) ) ? self
::toUnsigned6( $ip ) : self
::toUnsigned( $ip );
282 if ( $n !== false ) {
283 $n = sprintf( '%08X', $n );
289 * Given an IP address in dotted-quad notation, returns an unsigned integer.
290 * Like ip2long() except that it actually works and has a consistent error return value.
291 * Comes from ProxyTools.php
292 * @param $ip Quad dotted IP address.
295 public static function toUnsigned( $ip ) {
296 // Use IPv6 function if we have an that sort of IP
297 if ( self
::isIPv6( $ip ) ) {
298 return toUnsigned6( $ip );
300 if ( $ip == '255.255.255.255' ) {
304 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
315 * Convert a dotted-quad IP to a signed integer
316 * Returns false on failure
318 public static function toSigned( $ip ) {
319 if ( $ip == '255.255.255.255' ) {
331 * Convert a network specification in CIDR notation to an integer network and a number of bits
332 * @return array(string, int)
334 public static function parseCIDR( $range ) {
335 $parts = explode( '/', $range, 2 );
336 if ( count( $parts ) != 2 ) {
337 return array( false, false );
339 $network = self
::toSigned( $parts[0] );
340 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
345 $network &= ~
((1 << (32 - $bits)) - 1);
347 # Convert to unsigned
348 if ( $network < 0 ) {
349 $network +
= pow( 2, 32 );
355 return array( $network, $bits );
359 * Given a string range in a number of formats, return the start and end of
360 * the range in hexadecimal. For IPv4.
364 * 1.2.3.4 - 1.2.3.5 Explicit range
366 * @return array(string, int)
368 public static function parseRange( $range ) {
369 // Use IPv6 function if we have an that sort of IP
370 if ( self
::isIPv6( $ip ) ) {
371 return self
::parseRange6( $range );
373 if ( strpos( $range, '/' ) !== false ) {
375 list( $network, $bits ) = self
::parseCIDR( $range );
376 if ( $network === false ) {
377 $start = $end = false;
379 $start = sprintf( '%08X', $network );
380 $end = sprintf( '%08X', $network +
pow( 2, (32 - $bits) ) - 1 );
382 } elseif ( strpos( $range, '-' ) !== false ) {
384 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
385 $start = self
::toUnsigned( $start ); $end = self
::toUnsigned( $end );
386 if ( $start > $end ) {
387 $start = $end = false;
389 $start = sprintf( '%08X', $start );
390 $end = sprintf( '%08X', $end );
394 $start = $end = self
::toHex( $range );
396 if ( $start === false ||
$end === false ) {
397 return array( false, false );
399 return array( $start, $end );
404 * Determine if a given IPv4 address is in a given CIDR network
405 * @param $addr The address to check against the given range.
406 * @param $range The range to check the given address against.
407 * @return bool Whether or not the given address is in the given range.
409 public static function isInRange( $addr, $range ) {
410 // Convert to IPv6 if needed
411 $unsignedIP = self
::toUnsigned6( self
::IPv4toIPv6($addr) );
412 list( $start, $end ) = self
::parseRange6( self
::IPv4toIPv6($range) );
413 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
417 * Convert some unusual representations of IPv4 addresses to their
418 * canonical dotted quad representation.
420 * This currently only checks a few IPV4-to-IPv6 related cases. More
421 * unusual representations may be added later.
423 * @param $addr something that might be an IP address
424 * @return valid dotted quad IPv4 address or null
426 public static function canonicalize( $addr ) {
427 if ( self
::isValid( $addr ) )
430 // IPv6 loopback address
432 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) )
435 // IPv4-mapped and IPv4-compatible IPv6 addresses
436 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) )
438 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
439 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
441 return null; // give up