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 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
27 define( 'IP_ADDRESS_STRING', RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)|' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)');
31 * Given a string, determine if it as valid IP
32 * Unlike isValid(), this looks for networks too
33 * @param $ip IP address.
36 public function isIPAddress( $ip ) {
37 if ( !$ip ) return false;
38 return preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip);
42 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
43 * See http://www.answers.com/topic/ipv4-compatible-address
44 * IPs with the first 92 bits as zeros are reserved from IPv6
45 * @param $ip quad-dotted IP address.
48 public function IPv4toIPv6( $ip ) {
49 if ( !$ip ) return null;
50 // Convert only if needed
51 if ( strpos($ip,':') !==false ) return $ip;
53 if ( strpos( $ip, '/' ) !== false ) {
54 $parts = explode( '/', $ip, 2 );
55 if ( count( $parts ) != 2 ) {
58 $network = IP
::toUnsigned( $parts[0] );
59 $bits = $parts[1] +
96;
60 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
61 return IP
::toOctet( $network ) . "/$bits";
66 return IP
::toOctet( IP
::toUnsigned( $ip ) );
70 * Given an IPv6 address in octet notation, returns an unsigned integer.
71 * @param $ip octet ipv6 IP address.
74 public function toUnsigned6( $ip ) {
75 if ( !$ip ) return null;
76 $ip = explode(':', IP
::expandIP( $ip ) );
79 $r_ip .= wfBaseConvert( $v, 16, 2, 16);
81 return wfBaseConvert($r_ip, 2, 10);
85 * Given an IPv6 address in octet notation, returns the expanded octet.
86 * @param $ip octet ipv6 IP address.
89 public function expandIP( $ip ) {
90 if ( !$ip ) return null;
91 // Only IPv6 addresses can be expanded
92 if ( strpos($ip,':') === false ) return $ip;
93 // Expand zero abbreviations
94 if ( substr_count($ip, '::') ) {
95 $ip = str_replace('::', str_repeat(':0000', 8 - substr_count($ip, ':')) . ':', $ip);
101 * Given an unsigned integer, returns an IPv6 address in octet notation
102 * @param $ip integer ipv6 IP address.
105 public function toOctet( $ip_int ) {
106 // Convert integer to binary
107 $ip_int = wfBaseConvert($ip_int, 10, 2, 128);
108 // Seperate into 8 octets
109 $ip_oct = base_convert( substr( $ip_int, 0, 16 ), 2, 16 );
110 for ($n=1; $n < 8; $n++
) {
111 // Convert to hex, and add ":" marks
112 $ip_oct .= ':' . base_convert( substr($ip_int, 16*$n, 16), 2, 16 );
118 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
119 * @return array(string, int)
121 public static function parseCIDR6( $range ) {
122 $parts = explode( '/', $range, 2 );
123 if ( count( $parts ) != 2 ) {
124 return array( false, false );
126 $network = IP
::toUnsigned6( $parts[0] );
127 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
132 # Native 32 bit functions WONT work here!!!
133 # Convert to a padded binary number
134 $network = wfBaseConvert( $network, 10, 2, 128 );
135 # Truncate the last (128-$bits) bits and replace them with zeros
136 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
137 # Convert back to an integer
138 $network = wfBaseConvert( $network, 2, 10 );
145 return array( $network, $bits );
149 * Given a string range in a number of formats, return the start and end of
150 * the range in hexadecimal. For IPv6.
153 * 2001:0db8:85a3::7344/96 CIDR
154 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
155 * 2001:0db8:85a3::7344/96 Single IP
156 * @return array(string, int)
158 public static function parseRange6( $range ) {
159 if ( strpos( $range, '/' ) !== false ) {
161 list( $network, $bits ) = IP
::parseCIDR6( $range );
162 if ( $network === false ) {
163 $start = $end = false;
165 $start = sprintf( '%08X', $network );
166 $end = sprintf( '%08X', $network +
pow( 2, (128 - $bits) ) - 1 );
168 } elseif ( strpos( $range, '-' ) !== false ) {
170 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
171 $start = IP
::toUnsigned6( $start ); $end = IP
::toUnsigned6( $end );
172 if ( $start > $end ) {
173 $start = $end = false;
175 $start = sprintf( '%08X', $start );
176 $end = sprintf( '%08X', $end );
180 $start = $end = IP
::toHex6( $range );
182 if ( $start === false ||
$end === false ) {
183 return array( false, false );
185 return array( $start, $end );
190 * Validate an IP address.
191 * @return boolean True if it is valid.
193 public static function isValid( $ip ) {
194 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip) );
198 * Validate an IP Block.
199 * @return boolean True if it is valid.
201 public static function isValidBlock( $ipblock ) {
202 return ( count(self
::toArray($ipblock)) == 1 +
5 );
206 * Determine if an IP address really is an IP address, and if it is public,
207 * i.e. not RFC 1918 or similar
208 * Comes from ProxyTools.php
210 public static function isPublic( $ip ) {
211 $n = IP
::toUnsigned( $ip );
216 // ip2long accepts incomplete addresses, as well as some addresses
217 // followed by garbage characters. Check that it's really valid.
218 if( $ip != long2ip( $n ) ) {
222 static $privateRanges = false;
223 if ( !$privateRanges ) {
224 $privateRanges = array(
225 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
226 array( '172.16.0.0', '172.31.255.255' ), # "
227 array( '192.168.0.0', '192.168.255.255' ), # "
228 array( '0.0.0.0', '0.255.255.255' ), # this network
229 array( '127.0.0.0', '127.255.255.255' ), # loopback
233 foreach ( $privateRanges as $r ) {
234 $start = IP
::toUnsigned( $r[0] );
235 $end = IP
::toUnsigned( $r[1] );
236 if ( $n >= $start && $n <= $end ) {
244 * Split out an IP block as an array of 4 bytes and a mask,
245 * return false if it can't be determined
247 * @parameter $ip string A quad dotted IP address
250 public static function toArray( $ipblock ) {
252 if(! preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:'.RE_IP_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
260 * Return a zero-padded hexadecimal representation of an IP address.
262 * Hexadecimal addresses are used because they can easily be extended to
263 * IPv6 support. To separate the ranges, the return value from this
264 * function for an IPv6 address will be prefixed with "v6-", a non-
265 * hexadecimal string which sorts after the IPv4 addresses.
267 * @param $ip Quad dotted IP address.
268 * @return hexidecimal
270 public static function toHex( $ip ) {
271 $n = self
::toUnsigned( $ip );
272 if ( $n !== false ) {
273 $n = sprintf( '%08X', $n );
279 public static function toHex6( $ip ) {
280 $n = self
::toUnsigned6( $ip );
281 if ( $n !== false ) {
282 $n = sprintf( '%08X', $n );
288 * Given an IP address in dotted-quad notation, returns an unsigned integer.
289 * Like ip2long() except that it actually works and has a consistent error return value.
290 * Comes from ProxyTools.php
291 * @param $ip Quad dotted IP address.
294 public static function toUnsigned( $ip ) {
295 if ( $ip == '255.255.255.255' ) {
299 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
310 * Convert a dotted-quad IP to a signed integer
311 * Returns false on failure
313 public static function toSigned( $ip ) {
314 if ( $ip == '255.255.255.255' ) {
326 * Convert a network specification in CIDR notation to an integer network and a number of bits
327 * @return array(string, int)
329 public static function parseCIDR( $range ) {
330 $parts = explode( '/', $range, 2 );
331 if ( count( $parts ) != 2 ) {
332 return array( false, false );
334 $network = IP
::toSigned( $parts[0] );
335 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
340 $network &= ~
((1 << (32 - $bits)) - 1);
342 # Convert to unsigned
343 if ( $network < 0 ) {
344 $network +
= pow( 2, 32 );
350 return array( $network, $bits );
354 * Given a string range in a number of formats, return the start and end of
355 * the range in hexadecimal. For IPv4.
359 * 1.2.3.4 - 1.2.3.5 Explicit range
361 * @return array(string, int)
363 public static function parseRange( $range ) {
364 if ( strpos( $range, '/' ) !== false ) {
366 list( $network, $bits ) = IP
::parseCIDR( $range );
367 if ( $network === false ) {
368 $start = $end = false;
370 $start = sprintf( '%08X', $network );
371 $end = sprintf( '%08X', $network +
pow( 2, (32 - $bits) ) - 1 );
373 } elseif ( strpos( $range, '-' ) !== false ) {
375 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
376 $start = IP
::toUnsigned( $start ); $end = IP
::toUnsigned( $end );
377 if ( $start > $end ) {
378 $start = $end = false;
380 $start = sprintf( '%08X', $start );
381 $end = sprintf( '%08X', $end );
385 $start = $end = IP
::toHex( $range );
387 if ( $start === false ||
$end === false ) {
388 return array( false, false );
390 return array( $start, $end );
395 * Determine if a given IPv4 address is in a given CIDR network
396 * @param $addr The address to check against the given range.
397 * @param $range The range to check the given address against.
398 * @return bool Whether or not the given address is in the given range.
400 public static function isInRange( $addr, $range ) {
401 // Convert to IPv6 if needed
402 $unsignedIP = IP
::toUnsigned6( IP
::IPv4toIPv6($addr) );
403 list( $start, $end ) = IP
::parseRange6( IP
::IPv4toIPv6($range) );
404 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
408 * Convert some unusual representations of IPv4 addresses to their
409 * canonical dotted quad representation.
411 * This currently only checks a few IPV4-to-IPv6 related cases. More
412 * unusual representations may be added later.
414 * @param $addr something that might be an IP address
415 * @return valid dotted quad IPv4 address or null
417 public static function canonicalize( $addr ) {
418 if ( IP
::isValid( $addr ) )
421 // IPv6 loopback address
423 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) )
426 // IPv4-mapped and IPv4-compatible IPv6 addresses
427 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) )
429 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
430 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
432 return null; // give up