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 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
::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 IP address.
114 public function toOctet( $ip_int ) {
115 $ip_int = strval($ip_int);
116 // Convert integer to binary
117 $ip_int = wfBaseConvert($ip_int, 10, 2, 128);
118 // Seperate into 8 octets
119 $ip_oct = base_convert( substr( $ip_int, 0, 16 ), 2, 16 );
120 for ($n=1; $n < 8; $n++
) {
121 // Convert to hex, and add ":" marks
122 $ip_oct .= ':' . base_convert( substr($ip_int, 16*$n, 16), 2, 16 );
128 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
129 * @return array(string, int)
131 public static function parseCIDR6( $range ) {
132 $parts = explode( '/', $range, 2 );
133 if ( count( $parts ) != 2 ) {
134 return array( false, false );
136 $network = self
::toUnsigned6( $parts[0] );
137 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
142 # Native 32 bit functions WONT work here!!!
143 # Convert to a padded binary number
144 $network = wfBaseConvert( $network, 10, 2, 128 );
145 # Truncate the last (128-$bits) bits and replace them with zeros
146 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
147 # Convert back to an integer
148 $network = wfBaseConvert( $network, 2, 10 );
155 return array( $network, $bits );
159 * Given a string range in a number of formats, return the start and end of
160 * the range in hexadecimal. For IPv6.
163 * 2001:0db8:85a3::7344/96 CIDR
164 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
165 * 2001:0db8:85a3::7344/96 Single IP
166 * @return array(string, int)
168 public static function parseRange6( $range ) {
169 if ( strpos( $range, '/' ) !== false ) {
171 list( $network, $bits ) = self
::parseCIDR6( $range );
172 if ( $network === false ) {
173 $start = $end = false;
175 $start = sprintf( '%08X', $network );
176 $end = sprintf( '%08X', $network +
pow( 2, (128 - $bits) ) - 1 );
178 } elseif ( strpos( $range, '-' ) !== false ) {
180 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
181 $start = self
::toUnsigned6( $start ); $end = self
::toUnsigned6( $end );
182 if ( $start > $end ) {
183 $start = $end = false;
185 $start = sprintf( '%08X', $start );
186 $end = sprintf( '%08X', $end );
190 $start = $end = self
::toHex( $range );
192 if ( $start === false ||
$end === false ) {
193 return array( false, false );
195 return array( $start, $end );
200 * Validate an IP address.
201 * @return boolean True if it is valid.
203 public static function isValid( $ip ) {
204 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip) );
208 * Validate an IP Block.
209 * @return boolean True if it is valid.
211 public static function isValidBlock( $ipblock ) {
212 return ( count(self
::toArray($ipblock)) == 1 +
5 );
216 * Determine if an IP address really is an IP address, and if it is public,
217 * i.e. not RFC 1918 or similar
218 * Comes from ProxyTools.php
220 public static function isPublic( $ip ) {
221 $n = self
::toUnsigned( $ip );
226 // ip2long accepts incomplete addresses, as well as some addresses
227 // followed by garbage characters. Check that it's really valid.
228 if( $ip != long2ip( $n ) ) {
232 static $privateRanges = false;
233 if ( !$privateRanges ) {
234 $privateRanges = array(
235 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
236 array( '172.16.0.0', '172.31.255.255' ), # "
237 array( '192.168.0.0', '192.168.255.255' ), # "
238 array( '0.0.0.0', '0.255.255.255' ), # this network
239 array( '127.0.0.0', '127.255.255.255' ), # loopback
243 foreach ( $privateRanges as $r ) {
244 $start = self
::toUnsigned( $r[0] );
245 $end = self
::toUnsigned( $r[1] );
246 if ( $n >= $start && $n <= $end ) {
254 * Split out an IP block as an array of 4 bytes and a mask,
255 * return false if it can't be determined
257 * @parameter $ip string A quad dotted/octet IP address
260 public static function toArray( $ipblock ) {
262 if( preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:'.RE_IP_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
264 } else if ( preg_match( '/^' . RE_IPV6_ADD
. '(?:\/(?:'.RE_IPV6_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
272 * Return a zero-padded hexadecimal representation of an IP address.
274 * Hexadecimal addresses are used because they can easily be extended to
275 * IPv6 support. To separate the ranges, the return value from this
276 * function for an IPv6 address will be prefixed with "v6-", a non-
277 * hexadecimal string which sorts after the IPv4 addresses.
279 * @param $ip Quad dotted IP address.
280 * @return hexidecimal
282 public static function toHex( $ip ) {
283 // Use IPv6 functions if needed
284 $n = ( self
::isIPv6($ip) ) ? self
::toUnsigned6( $ip ) : self
::toUnsigned( $ip );
285 if ( $n !== false ) {
286 $n = sprintf( '%08X', $n );
292 * Given an IP address in dotted-quad notation, returns an unsigned integer.
293 * Like ip2long() except that it actually works and has a consistent error return value.
294 * Comes from ProxyTools.php
295 * @param $ip Quad dotted IP address.
298 public static function toUnsigned( $ip ) {
299 // Use IPv6 functions if needed
300 if ( self
::isIPv6( $ip ) ) {
301 return toUnsigned6( $ip );
303 if ( $ip == '255.255.255.255' ) {
307 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
318 * Convert a dotted-quad IP to a signed integer
319 * Returns false on failure
321 public static function toSigned( $ip ) {
322 if ( $ip == '255.255.255.255' ) {
334 * Convert a network specification in CIDR notation to an integer network and a number of bits
335 * @return array(string, int)
337 public static function parseCIDR( $range ) {
338 $parts = explode( '/', $range, 2 );
339 if ( count( $parts ) != 2 ) {
340 return array( false, false );
342 $network = self
::toSigned( $parts[0] );
343 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
348 $network &= ~
((1 << (32 - $bits)) - 1);
350 # Convert to unsigned
351 if ( $network < 0 ) {
352 $network +
= pow( 2, 32 );
358 return array( $network, $bits );
362 * Given a string range in a number of formats, return the start and end of
363 * the range in hexadecimal. For IPv4.
367 * 1.2.3.4 - 1.2.3.5 Explicit range
369 * @return array(string, int)
371 public static function parseRange( $range ) {
372 // Use IPv6 functions if needed
373 if ( self
::isIPv6( $range ) ) {
374 return self
::parseRange6( $range );
376 if ( strpos( $range, '/' ) !== false ) {
378 list( $network, $bits ) = self
::parseCIDR( $range );
379 if ( $network === false ) {
380 $start = $end = false;
382 $start = sprintf( '%08X', $network );
383 $end = sprintf( '%08X', $network +
pow( 2, (32 - $bits) ) - 1 );
385 } elseif ( strpos( $range, '-' ) !== false ) {
387 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
388 $start = self
::toUnsigned( $start ); $end = self
::toUnsigned( $end );
389 if ( $start > $end ) {
390 $start = $end = false;
392 $start = sprintf( '%08X', $start );
393 $end = sprintf( '%08X', $end );
397 $start = $end = self
::toHex( $range );
399 if ( $start === false ||
$end === false ) {
400 return array( false, false );
402 return array( $start, $end );
407 * Determine if a given IPv4 address is in a given CIDR network
408 * @param $addr The address to check against the given range.
409 * @param $range The range to check the given address against.
410 * @return bool Whether or not the given address is in the given range.
412 public static function isInRange( $addr, $range ) {
413 // Convert to IPv6 if needed
414 $unsignedIP = self
::toUnsigned6( self
::IPv4toIPv6($addr) );
415 list( $start, $end ) = self
::parseRange6( self
::IPv4toIPv6($range) );
416 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
420 * Convert some unusual representations of IPv4 addresses to their
421 * canonical dotted quad representation.
423 * This currently only checks a few IPV4-to-IPv6 related cases. More
424 * unusual representations may be added later.
426 * @param $addr something that might be an IP address
427 * @return valid dotted quad IPv4 address or null
429 public static function canonicalize( $addr ) {
430 if ( self
::isValid( $addr ) )
433 // IPv6 loopback address
435 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) )
438 // IPv4-mapped and IPv4-compatible IPv6 addresses
439 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) )
441 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
442 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
444 return null; // give up