29define(
'RE_IP_BYTE',
'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
32define(
'RE_IP_PREFIX',
'(3[0-2]|[12]?\d)' );
37define(
'RE_IPV6_WORD',
'([0-9A-Fa-f]{1,4})' );
38define(
'RE_IPV6_PREFIX',
'(12[0-8]|1[01][0-9]|[1-9]?\d)' );
53define(
'RE_IPV6_GAP',
':(?:0+:)*(?::(?:0+:)*)?' );
54define(
'RE_IPV6_V4_PREFIX',
'0*' .
RE_IPV6_GAP .
'(?:ffff:)?' );
57define(
'IP_ADDRESS_STRING',
79 public static function isIPAddress( $ip ) {
90 public static function isIPv6( $ip ) {
101 public static function isIPv4( $ip ) {
113 public static function isValid( $ip ) {
114 return ( preg_match(
'/^' .
RE_IP_ADD .
'$/', $ip )
129 || preg_match(
'/^' .
RE_IP_RANGE .
'$/', $ipRange ) );
149 if ( !self::isIPAddress( $ip ) ) {
152 if ( self::isIPv4( $ip ) ) {
154 $ip = preg_replace(
'!(?:^|(?<=\.))0+(?=[1-9]|0[./]|0$)!',
'', $ip );
158 $ip = strtoupper( $ip );
160 $abbrevPos = strpos( $ip,
'::' );
161 if ( $abbrevPos !==
false ) {
164 $CIDRStart = strpos( $ip,
"/" );
165 $addressEnd = ( $CIDRStart !== false )
169 if ( $abbrevPos == 0 ) {
171 $extra = ( $ip ==
'::' ) ?
'0' :
'';
174 } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
184 $ip = str_replace(
'::',
185 str_repeat( $repeat, $pad - substr_count( $ip,
':' ) ) . $extra,
190 $ip = preg_replace(
'/(^|:)0+(' .
RE_IPV6_WORD .
')/',
'$1$2', $ip );
203 $ip = self::sanitizeIP( $ip );
204 if ( self::isIPv6( $ip ) ) {
206 if ( strpos( $ip,
'/' ) !==
false ) {
207 list( $ip, $cidr ) = explode(
'/', $ip, 2 );
209 list( $ip, $cidr ) = [ $ip,
'' ];
213 $longest = $longestPos =
false;
215 '!(?:^|:)0(?::0)+(?:$|:)!', $ip, $m, PREG_OFFSET_CAPTURE, $offset
217 list( $match, $pos ) = $m[0];
218 if ( strlen( $match ) > strlen( $longest ) ) {
222 $offset = ( $pos + strlen( $match ) );
224 if ( $longest !==
false ) {
226 $ip = substr_replace( $ip,
'::', $longestPos, strlen( $longest ) );
229 if ( $cidr !==
'' ) {
230 $ip =
"{$ip}/{$cidr}";
233 $ip = strtolower( $ip );
256 if ( substr( $both, 0, 1 ) ===
'[' ) {
257 if ( preg_match(
'/^\[(' .
RE_IPV6_ADD .
')\](?::(?P<port>\d+))?$/', $both, $m ) ) {
258 if ( isset( $m[
'port'] ) ) {
259 return [ $m[1], intval( $m[
'port'] ) ];
261 return [ $m[1], false ];
268 $numColons = substr_count( $both,
':' );
269 if ( $numColons >= 2 ) {
271 if ( preg_match(
'/^' .
RE_IPV6_ADD .
'$/', $both ) ) {
272 return [ $both, false ];
278 if ( $numColons >= 1 ) {
280 $bits = explode(
':', $both );
281 if ( preg_match(
'/^\d+/', $bits[1] ) ) {
282 return [ $bits[0], intval( $bits[1] ) ];
290 return [ $both, false ];
305 if ( strpos( $host,
':' ) !==
false ) {
308 if ( $defaultPort !==
false && $port == $defaultPort ) {
311 return "$host:$port";
321 public static function formatHex( $hex ) {
322 if ( substr( $hex, 0, 3 ) ==
'v6-' ) {
323 return self::hexToOctet( substr( $hex, 3 ) );
325 return self::hexToQuad( $hex );
335 public static function hexToOctet( $ip_hex ) {
337 $ip_hex = str_pad( strtoupper( $ip_hex ), 32,
'0', STR_PAD_LEFT );
339 $ip_oct = substr( $ip_hex, 0, 4 );
340 for ( $n = 1; $n < 8; $n++ ) {
341 $ip_oct .=
':' . substr( $ip_hex, 4 * $n, 4 );
344 $ip_oct = preg_replace(
'/(^|:)0+(' .
RE_IPV6_WORD .
')/',
'$1$2', $ip_oct );
355 public static function hexToQuad( $ip_hex ) {
357 $ip_hex = str_pad( strtoupper( $ip_hex ), 8,
'0', STR_PAD_LEFT );
360 for ( $i = 0; $i < 4; $i++ ) {
364 $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
377 public static function isPublic( $ip ) {
378 static $privateSet =
null;
379 if ( !$privateSet ) {
380 $privateSet =
new IPSet( [
381 '10.0.0.0/8', # RFC 1918 (
private)
382 '172.16.0.0/12', # RFC 1918 (
private)
383 '192.168.0.0/16', # RFC 1918 (
private)
384 '0.0.0.0/8', #
this network
385 '127.0.0.0/8', # loopback
386 'fc00::/7', # RFC 4193 (local)
387 '0:0:0:0:0:0:0:1', # loopback
388 '169.254.0.0/16', # link-local
389 'fe80::/10', # link-local
392 return !$privateSet->match( $ip );
406 public static function toHex( $ip ) {
407 if ( self::isIPv6( $ip ) ) {
408 $n =
'v6-' . self::IPv6ToRawHex( $ip );
409 } elseif ( self::isIPv4( $ip ) ) {
412 $ip = self::sanitizeIP( $ip );
416 # On 32-bit platforms (and on Windows), 2^32 does not fit into an int,
417 # so $n becomes a float. We convert it to string instead.
418 if ( is_float( $n ) ) {
422 if ( $n !==
false ) {
423 # Floating points can handle the conversion; faster than Wikimedia\base_convert()
424 $n = strtoupper( str_pad( base_convert( $n, 10, 16 ), 8,
'0', STR_PAD_LEFT ) );
440 $ip = self::sanitizeIP( $ip );
445 foreach ( explode(
':', $ip ) as $v ) {
446 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
459 public static function parseCIDR( $range ) {
460 if ( self::isIPv6( $range ) ) {
461 return self::parseCIDR6( $range );
463 $parts = explode(
'/', $range, 2 );
464 if ( count( $parts ) != 2 ) {
465 return [
false, false ];
467 list( $network, $bits ) = $parts;
468 $network = ip2long( $network );
469 if ( $network !==
false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
473 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1 );
475 # Convert to unsigned
476 if ( $network < 0 ) {
484 return [ $network, $bits ];
504 if ( strpos( $range,
'/' ) !==
false ) {
505 if ( self::isIPv6( $range ) ) {
506 return self::parseRange6( $range );
508 list( $network, $bits ) = self::parseCIDR( $range );
509 if ( $network ===
false ) {
510 $start = $end =
false;
512 $start = sprintf(
'%08X', $network );
513 $end = sprintf(
'%08X', $network + 2 ** ( 32 - $bits ) - 1 );
516 } elseif ( strpos( $range,
'-' ) !==
false ) {
517 list( $start, $end ) = array_map(
'trim', explode(
'-', $range, 2 ) );
518 if ( self::isIPv6( $start ) && self::isIPv6( $end ) ) {
519 return self::parseRange6( $range );
521 if ( self::isIPv4( $start ) && self::isIPv4( $end ) ) {
522 $start = self::toHex( $start );
523 $end = self::toHex( $end );
524 if ( $start > $end ) {
525 $start = $end =
false;
528 $start = $end =
false;
532 $start = $end = self::toHex( $range );
534 if ( $start ===
false || $end ===
false ) {
535 return [
false, false ];
537 return [ $start, $end ];
549 private static function parseCIDR6( $range ) {
550 # Explode into <expanded IP,range>
551 $parts = explode(
'/', self::sanitizeIP( $range ), 2 );
552 if ( count( $parts ) != 2 ) {
553 return [
false, false ];
555 list( $network, $bits ) = $parts;
556 $network = self::IPv6ToRawHex( $network );
557 if ( $network !==
false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
561 # Native 32 bit functions WONT work here!!!
562 # Convert to a padded binary number
563 $network = Wikimedia\base_convert( $network, 16, 2, 128 );
564 # Truncate the last (128-$bits) bits and replace them with zeros
565 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
566 # Convert back to an integer
567 $network = Wikimedia\base_convert( $network, 2, 10 );
574 return [ $network, (int)$bits ];
592 $range = self::sanitizeIP( $range );
594 if ( strpos( $range,
'/' ) !==
false ) {
595 list( $network, $bits ) = self::parseCIDR6( $range );
596 if ( $network ===
false ) {
597 $start = $end =
false;
599 $start = Wikimedia\base_convert( $network, 10, 16, 32,
false );
600 # Turn network to binary (again)
601 $end = Wikimedia\base_convert( $network, 10, 2, 128 );
602 # Truncate the last (128-$bits) bits and replace them with ones
603 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
605 $end = Wikimedia\base_convert( $end, 2, 16, 32,
false );
606 # see toHex() comment
607 $start =
"v6-$start";
611 } elseif ( strpos( $range,
'-' ) !==
false ) {
612 list( $start, $end ) = array_map(
'trim', explode(
'-', $range, 2 ) );
613 $start = self::toHex( $start );
614 $end = self::toHex( $end );
615 if ( $start > $end ) {
616 $start = $end =
false;
620 $start = $end = self::toHex( $range );
622 if ( $start ===
false || $end ===
false ) {
623 return [
false, false ];
625 return [ $start, $end ];
639 public static function isInRange( $addr, $range ) {
640 $hexIP = self::toHex( $addr );
641 list( $start, $end ) = self::parseRange( $range );
643 return ( strcmp( $hexIP, $start ) >= 0 &&
644 strcmp( $hexIP, $end ) <= 0 );
657 public static function isInRanges( $ip, $ranges ) {
658 foreach ( $ranges as $range ) {
659 if ( self::isInRange( $ip, $range ) ) {
678 $addr = preg_replace(
'/\%.*/',
'', $addr );
680 if ( self::isValid( $addr ) ) {
684 if ( strpos( $addr,
':' ) !==
false && strpos( $addr,
'.' ) !==
false ) {
685 $addr = substr( $addr, strrpos( $addr,
':' ) + 1 );
686 if ( self::isIPv4( $addr ) ) {
692 if ( preg_match(
'/^0*' .
RE_IPV6_GAP .
'1$/', $addr, $m ) ) {
702 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
715 list( , $bits ) = self::parseCIDR( $range );
716 list( $start, ) = self::parseRange( $range );
717 $start = self::formatHex( $start );
718 if ( $bits ===
false ) {
722 return "$start/$bits";
731 public static function getSubnet( $ip ) {
734 if ( self::isIPv6( $ip ) ) {
735 $parts = self::parseRange(
"$ip/64" );
737 } elseif ( preg_match(
'/^(\d+\.\d+\.\d+)\.\d+$/', $ip,
$matches ) ) {
A collection of public static functions to play with IP address and IP ranges.
static combineHostAndPort( $host, $port, $defaultPort=false)
Given a host name and a port, combine them into host/port string like you might find in a URL.
static isValid( $ip)
Validate an IP address.
static prettifyIP( $ip)
Prettify an IP for display to end users.
static isIPv4( $ip)
Given a string, determine if it as valid IP in IPv4 only.
static parseRange( $range)
Given a string range in a number of formats, return the start and end of the range in hexadecimal.
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
static formatHex( $hex)
Convert an IPv4 or IPv6 hexadecimal representation back to readable format.
static parseCIDR6( $range)
Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits.
static IPv6ToRawHex( $ip)
Given an IPv6 address in octet notation, returns a pure hex string.
static canonicalize( $addr)
Convert some unusual representations of IPv4 addresses to their canonical dotted quad representation.
static getSubnet( $ip)
Returns the subnet of a given IP.
static parseRange6( $range)
Given a string range in a number of formats, return the start and end of the range in hexadecimal.
static sanitizeRange( $range)
Gets rid of unneeded numbers in quad-dotted/octet IP strings For example, 127.111....
static hexToQuad( $ip_hex)
Converts a hexadecimal number to an IPv4 address in quad-dotted notation.
static toHex( $ip)
Return a zero-padded upper case hexadecimal representation of an IP address.
static isPublic( $ip)
Determine if an IP address really is an IP address, and if it is public, i.e.
static hexToOctet( $ip_hex)
Converts a hexadecimal number to an IPv6 address in octet notation.
static isInRange( $addr, $range)
Determine if a given IPv4/IPv6 address is in a given CIDR network.
static isValidRange( $ipRange)
Validate an IP range (valid address with a valid CIDR prefix).
static isIPv6( $ip)
Given a string, determine if it as valid IP in IPv6 only.
static isInRanges( $ip, $ranges)
Determines if an IP address is a list of CIDR a.b.c.d/n ranges.
static parseCIDR( $range)
Convert a network specification in CIDR notation to an integer network and a number of bits.
static splitHostAndPort( $both)
Given a host/port string, like one might find in the host part of a URL per RFC 2732,...