IPv6.inc 26.1 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1 2 3 4 5 6 7 8
<?php

/**
 * This file contains the implementation of the Net_IPv6 class
 *
 * PHP versions 4 and 5
 *
 * LICENSE: This source file is subject to the New BSD license, that is
9
 * available through the world-wide-web at
Ad Schellevis's avatar
Ad Schellevis committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
 * http://www.opensource.org/licenses/bsd-license.php
 * If you did not receive a copy of the new BSDlicense and are unable
 * to obtain it through the world-wide-web, please send a note to
 * license@php.net so we can mail you a copy immediately
 *
 * @category  Net
 * @package   Net_IPv6
 * @author    Alexander Merz <alexander.merz@web.de>
 * @copyright 2003-2005 The PHP Group
 * @license   BSD License http://www.opensource.org/licenses/bsd-license.php
 * @version   CVS: $Id$
 * @link      http://pear.php.net/package/Net_IPv6
 */

// {{{ constants

/**
 * Error message if netmask bits was not found
 * @see isInNetmask
 */
define("NET_IPV6_NO_NETMASK_MSG", "Netmask length not found");

/**
 * Error code if netmask bits was not found
 * @see isInNetmask
 */
define("NET_IPV6_NO_NETMASK", 10);

/**
 * Address Type: Unassigned (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_UNASSIGNED", 1);

/**
 * Address Type: Reserved (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_RESERVED", 11);

/**
 * Address Type: Reserved for NSAP Allocation (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_RESERVED_NSAP", 12);

/**
 * Address Type: Reserved for IPX Allocation (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_RESERVED_IPX", 13);

/**
63
 * Address Type: Reserved for Geographic-Based Unicast Addresses
Ad Schellevis's avatar
Ad Schellevis committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
 * (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_RESERVED_UNICAST_GEOGRAPHIC", 14);

/**
 * Address Type: Provider-Based Unicast Address (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_UNICAST_PROVIDER", 22);

/**
 * Address Type: Multicast Addresses (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_MULTICAST", 31);

/**
 * Address Type: Link Local Use Addresses (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_LOCAL_LINK", 42);

/**
 * Address Type: Link Local Use Addresses (RFC 1884, Section 2.3)
 * @see getAddressType()
 */
define("NET_IPV6_LOCAL_SITE", 43);

/**
 * Address Type: Address range to embedded IPv4 ip in an IPv6 address (RFC 4291, Section 2.5.5)
 * @see getAddressType()
 */
define("NET_IPV6_IPV4MAPPING", 51);

/**
 * Address Type: Unspecified (RFC 4291, Section 2.5.2)
 * @see getAddressType()
 */
define("NET_IPV6_UNSPECIFIED", 52);

/**
 * Address Type: Unspecified (RFC 4291, Section 2.5.3)
 * @see getAddressType()
 */
define("NET_IPV6_LOOPBACK", 53);

/**
 * Address Type: address can not assigned to a specific type
 * @see getAddressType()
 */
define("NET_IPV6_UNKNOWN_TYPE", 1001);

// }}}
// {{{ Net_IPv6

/**
 * Class to validate and to work with IPv6 addresses.
 *
 * @category  Net
 * @package   Net_IPv6
 * @author    Alexander Merz <alexander.merz@web.de>
 * @author    <elfrink at introweb dot nl>
 * @author    Josh Peck <jmp at joshpeck dot org>
 * @copyright 2003-2010 The PHP Group
 * @license   BSD License http://www.opensource.org/licenses/bsd-license.php
 * @version   Release: 1.1.0RC5
 * @link      http://pear.php.net/package/Net_IPv6
 */
class Net_IPv6
{

    // {{{ separate()
    /**
     * Separates an IPv6 address into the address and a prefix length part
     *
     * @param String $ip the (compressed) IP as Hex representation
     *
     * @return Array the first element is the IP, the second the prefix length
     * @since  1.2.0
     * @access public
145
     * @static
Ad Schellevis's avatar
Ad Schellevis committed
146
     */
147
    public static function separate($ip)
Ad Schellevis's avatar
Ad Schellevis committed
148
    {
149

Ad Schellevis's avatar
Ad Schellevis committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        $addr = $ip;
        $spec = '';

        if(false === strrpos($ip, '/')) {

            return array($addr, $spec);

        }

        $elements = explode('/', $ip);

        if(2 == count($elements)) {

            $addr = $elements[0];
            $spec = $elements[1];

        }

        return array($addr, $spec);

    }
    // }}}

    // {{{ removeNetmaskSpec()

    /**
     * Removes a possible existing prefix length/ netmask specification at an IP address.
     *
     * @param String $ip the (compressed) IP as Hex representation
     *
     * @return String the IP without netmask length
     * @since  1.1.0
     * @access public
     * @static
     */
185
    public static function removeNetmaskSpec($ip)
Ad Schellevis's avatar
Ad Schellevis committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199
    {

        $elements = Net_IPv6::separate($ip);

        return $elements[0];

    }
    // }}}
    // {{{ removePrefixLength()

    /**
     * Tests for a prefix length specification in the address
     * and removes the prefix length, if exists
     *
200
     * The method is technically identical to removeNetmaskSpec() and
Ad Schellevis's avatar
Ad Schellevis committed
201 202 203 204 205 206 207 208 209 210
     * will be dropped in a future release.
     *
     * @param String $ip a valid ipv6 address
     *
     * @return String the address without a prefix length
     * @access public
     * @static
     * @see removeNetmaskSpec()
     * @deprecated
     */
211
    public static function removePrefixLength($ip)
Ad Schellevis's avatar
Ad Schellevis committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    {
        $pos = strrpos($ip, '/');

        if (false !== $pos) {

            return substr($ip, 0, $pos);

        }

        return $ip;
    }

    // }}}
    // {{{ getNetmaskSpec()

    /**
     * Returns a possible existing prefix length/netmask specification on an IP address.
     *
     * @param String $ip the (compressed) IP as Hex representation
     *
     * @return String the netmask spec
     * @since  1.1.0
     * @access public
     * @static
     */
237
    public static function getNetmaskSpec($ip)
Ad Schellevis's avatar
Ad Schellevis committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    {

        $elements = Net_IPv6::separate($ip);

        return $elements[1];

    }

    // }}}
    // {{{ getPrefixLength()

    /**
     * Tests for a prefix length specification in the address
     * and returns the prefix length, if exists
     *
253
     * The method is technically identical to getNetmaskSpec() and
Ad Schellevis's avatar
Ad Schellevis committed
254 255 256 257 258 259 260 261 262
     * will be dropped in a future release.
     *
     * @param String $ip a valid ipv6 address
     *
     * @return Mixed the prefix as String or false, if no prefix was found
     * @access public
     * @static
     * @deprecated
     */
263
    public static function getPrefixLength($ip)
Ad Schellevis's avatar
Ad Schellevis committed
264
    {
265
        if (preg_match("/^([0-9a-fA-F:]{2,39})\/(\d{1,3})*$/",
Ad Schellevis's avatar
Ad Schellevis committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
                        $ip, $matches)) {

            return $matches[2];

        } else {

            return false;

        }

    }

    // }}}
    // {{{ getNetmask()

    /**
     * Calculates the network prefix based on the netmask bits.
     *
     * @param String $ip   the (compressed) IP in Hex format
     * @param int    $bits if the number of netmask bits is not part of the IP
     *                     you must provide the number of bits
     *
     * @return String the network prefix
     * @since  1.1.0
     * @access public
     * @static
     */
293
    public static function getNetmask($ip, $bits = null)
Ad Schellevis's avatar
Ad Schellevis committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    {
        if (null==$bits) {

            $elements = explode('/', $ip);

            if (2 == count($elements)) {

                $addr = $elements[0];
                $bits = $elements[1];

            } else {

                include_once 'PEAR.inc';

                return PEAR::raiseError(NET_IPV6_NO_NETMASK_MSG,
                                        NET_IPV6_NO_NETMASK);
            }

        } else {

            $addr = $ip;

        }

        $addr       = Net_IPv6::uncompress($addr);
        $binNetmask = str_repeat('1', $bits).str_repeat('0', 128 - $bits);

        return Net_IPv6::_bin2Ip(Net_IPv6::_ip2Bin($addr) & $binNetmask);
    }

    // }}}
    // {{{ isInNetmask()

    /**
     * Checks if an (compressed) IP is in a specific address space.
     *
     * If the IP does not contain the number of netmask bits (F8000::FFFF/16)
     * then you have to use the $bits parameter.
     *
     * @param String $ip      the IP to check (eg. F800::FFFF)
     * @param String $netmask the netmask (eg F800::)
     * @param int    $bits    the number of netmask bits to compare,
     *                        if not given in $ip
     *
     * @return boolean true if $ip is in the netmask
     * @since  1.1.0
     * @access public
     * @static
     */
343
    public static function isInNetmask($ip, $netmask, $bits=null)
Ad Schellevis's avatar
Ad Schellevis committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    {
        // try to get the bit count

        if (null == $bits) {

            $elements = explode('/', $ip);

            if (2 == count($elements)) {

                $ip   = $elements[0];
                $bits = $elements[1];

            } else if (null == $bits) {

                $elements = explode('/', $netmask);

                if (2 == count($elements)) {

                     $netmask = $elements[0];
                     $bits    = $elements[1];

                }

                if (null == $bits) {

                    include_once 'PEAR.inc';
                    return PEAR::raiseError(NET_IPV6_NO_NETMASK_MSG,
                                            NET_IPV6_NO_NETMASK);

                }

            }

        }

        $binIp      = Net_IPv6::_ip2Bin(Net_IPv6::removeNetmaskSpec($ip));
        $binNetmask = Net_IPv6::_ip2Bin(Net_IPv6::removeNetmaskSpec($netmask));

        if (null != $bits
            && "" != $bits
            && 0 == strncmp($binNetmask, $binIp, $bits)) {

            return true;

        }

        return false;
    }

    // }}}
    // {{{ getAddressType()

    /**
     * Returns the type of an IPv6 address.
     *
     * RFC 2373, Section 2.3 describes several types of addresses in
     * the IPv6 address space.
     * Several address types are markers for reserved spaces and as
     * a consequence are subject to change.
     *
     * @param String $ip the IP address in Hex format,
     *                    compressed IPs are allowed
     *
     * @return int one of the address type constants
     * @access public
     * @since  1.1.0
     * @static
     *
     * @see    NET_IPV6_UNASSIGNED
     * @see    NET_IPV6_RESERVED
     * @see    NET_IPV6_RESERVED_NSAP
     * @see    NET_IPV6_RESERVED_IPX
     * @see    NET_IPV6_RESERVED_UNICAST_GEOGRAPHIC
     * @see    NET_IPV6_UNICAST_PROVIDER
     * @see    NET_IPV6_MULTICAST
     * @see    NET_IPV6_LOCAL_LINK
     * @see    NET_IPV6_LOCAL_SITE
421 422 423
     * @see    NET_IPV6_IPV4MAPPING
     * @see    NET_IPV6_UNSPECIFIED
     * @see    NET_IPV6_LOOPBACK
Ad Schellevis's avatar
Ad Schellevis committed
424 425
     * @see    NET_IPV6_UNKNOWN_TYPE
     */
426
    public static function getAddressType($ip)
Ad Schellevis's avatar
Ad Schellevis committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440
    {
        $ip    = Net_IPv6::removeNetmaskSpec($ip);
        $binip = Net_IPv6::_ip2Bin($ip);

        if(0 == strncmp(str_repeat('0', 128), $binip, 128)) { // ::/128

            return NET_IPV6_UNSPECIFIED;

        } else if(0 == strncmp(str_repeat('0', 127).'1', $binip, 128)) { // ::/128

            return NET_IPV6_LOOPBACK;

        } else if (0 == strncmp(str_repeat('0', 80).str_repeat('1', 16), $binip, 96)) { // ::ffff/96

441
            return NET_IPV6_IPV4MAPPING;
Ad Schellevis's avatar
Ad Schellevis committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

        } else if (0 == strncmp('1111111010', $binip, 10)) {

            return NET_IPV6_LOCAL_LINK;

        } else if (0 == strncmp('1111111011', $binip, 10)) {

            return NET_IPV6_LOCAL_SITE;

        } else if (0 == strncmp('111111100', $binip, 9)) {

            return NET_IPV6_UNASSIGNED;

        } else if (0 == strncmp('11111111', $binip, 8)) {

            return NET_IPV6_MULTICAST;

459
        } else if (0 == strncmp('00000000', $binip, 8)) {
Ad Schellevis's avatar
Ad Schellevis committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522

            return NET_IPV6_RESERVED;

        } else if (0 == strncmp('00000001', $binip, 8)
                    || 0 == strncmp('1111110', $binip, 7)) {

            return NET_IPV6_UNASSIGNED;

        } else if (0 == strncmp('0000001', $binip, 7)) {

            return NET_IPV6_RESERVED_NSAP;

        } else if (0 == strncmp('0000010', $binip, 7)) {

            return NET_IPV6_RESERVED_IPX;

        } else if (0 == strncmp('0000011', $binip, 7) ||
                    0 == strncmp('111110', $binip, 6) ||
                    0 == strncmp('11110', $binip, 5) ||
                    0 == strncmp('00001', $binip, 5) ||
                    0 == strncmp('1110', $binip, 4) ||
                    0 == strncmp('0001', $binip, 4) ||
                    0 == strncmp('001', $binip, 3) ||
                    0 == strncmp('011', $binip, 3) ||
                    0 == strncmp('101', $binip, 3) ||
                    0 == strncmp('110', $binip, 3)) {

            return NET_IPV6_UNASSIGNED;

        } else if (0 == strncmp('010', $binip, 3)) {

            return NET_IPV6_UNICAST_PROVIDER;

        } else if (0 == strncmp('100', $binip, 3)) {

            return NET_IPV6_RESERVED_UNICAST_GEOGRAPHIC;

        }

        return NET_IPV6_UNKNOWN_TYPE;
    }

    // }}}
    // {{{ Uncompress()

    /**
     * Uncompresses an IPv6 address
     *
     * RFC 2373 allows you to compress zeros in an address to '::'. This
     * function expects a valid IPv6 address and expands the '::' to
     * the required zeros.
     *
     * Example:  FF01::101  ->  FF01:0:0:0:0:0:0:101
     *           ::1        ->  0:0:0:0:0:0:0:1
     *
     * Note: You can also pass an invalid IPv6 address (usually as part of the process
     * of validation by checkIPv6, which will validate the return string).
     * This function will insert the "0" between "::" even if this results in too many
     * numbers in total. It is NOT the purpose of this function to validate your input.
     *
     * Example of calling with invalid input: 1::2:3:4:5:6:7:8:9 -> 1:0:2:3:4:5:6:7:8:9
     *
     * @param String $ip a (possibly) valid IPv6-address (hex format)
523 524 525 526
     * @param Boolean $leadingZeros if true, leading zeros are added to each
     *                              block of the address
     *                              (FF01::101  ->
     *                               FF01:0000:0000:0000:0000:0000:0000:0101)
Ad Schellevis's avatar
Ad Schellevis committed
527 528 529 530 531 532 533
     *
     * @return String the uncompressed IPv6-address (hex format)
     * @access public
     * @see Compress()
     * @static
     * @author Pascal Uhlmann
     */
534
    public static function uncompress($ip, $leadingZeros = false)
Ad Schellevis's avatar
Ad Schellevis committed
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
    {

        $prefix = Net_IPv6::getPrefixLength($ip);

        if (false === $prefix) {

            $prefix = '';

        } else {

            $ip     = Net_IPv6::removePrefixLength($ip);
            $prefix = '/'.$prefix;

        }

        $netmask = Net_IPv6::getNetmaskSpec($ip);
        $uip     = Net_IPv6::removeNetmaskSpec($ip);

        $c1 = -1;
        $c2 = -1;

        if (false !== strpos($uip, '::') ) {

            list($ip1, $ip2) = explode('::', $uip);

            if ("" == $ip1) {

                $c1 = -1;

            } else {

                $pos = 0;

                if (0 < ($pos = substr_count($ip1, ':'))) {

                    $c1 = $pos;

                } else {

                    $c1 = 0;

                }
            }
            if ("" == $ip2) {

                $c2 = -1;

            } else {

                $pos = 0;

                if (0 < ($pos = substr_count($ip2, ':'))) {

                    $c2 = $pos;

                } else {

                    $c2 = 0;

                }

            }

            if (strstr($ip2, '.')) {

                $c2++;

            }
            if (-1 == $c1 && -1 == $c2) { // ::

                $uip = "0:0:0:0:0:0:0:0";

            } else if (-1 == $c1) {              // ::xxx

                $fill = str_repeat('0:', 7-$c2);
                $uip  = str_replace('::', $fill, $uip);

            } else if (-1 == $c2) {              // xxx::

                $fill = str_repeat(':0', 7-$c1);
                $uip  = str_replace('::', $fill, $uip);

            } else {                          // xxx::xxx

                $fill = str_repeat(':0:', max(1, 6-$c2-$c1));
                $uip  = str_replace('::', $fill, $uip);
                $uip  = str_replace('::', ':', $uip);

            }
        }

        if(true == $leadingZeros) {
627

Ad Schellevis's avatar
Ad Schellevis committed
628 629 630 631 632 633
            $uipT    = array();
            $uiparts = explode(':', $uip);

            foreach($uiparts as $p) {

                $uipT[] = sprintf('%04s', $p);
634

Ad Schellevis's avatar
Ad Schellevis committed
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
            }

            $uip = implode(':', $uipT);
        }

        if ('' != $netmask) {

                $uip = $uip.'/'.$netmask;

        }

        return $uip.$prefix;
    }

    // }}}
    // {{{ Compress()

    /**
     * Compresses an IPv6 address
     *
     * RFC 2373 allows you to compress zeros in an address to '::'. This
     * function expects a valid IPv6 address and compresses successive zeros
     * to '::'
     *
     * Example:  FF01:0:0:0:0:0:0:101   -> FF01::101
     *           0:0:0:0:0:0:0:1        -> ::1
     *
662
     * When $ip is an already compressed address and $force is false, the method returns
Ad Schellevis's avatar
Ad Schellevis committed
663 664 665 666 667 668
     * the value as is, even if the address can be compressed further.
     *
     * Example: FF01::0:1 -> FF01::0:1
     *
     * To enforce maximum compression, you can set the second argument $force to true.
     *
669
     * Example: FF01::0:1 -> FF01::1
Ad Schellevis's avatar
Ad Schellevis committed
670 671 672 673 674 675 676 677 678 679
     *
     * @param String  $ip    a valid IPv6-address (hex format)
     * @param boolean $force if true the address will be compressed as best as possible (since 1.2.0)
     *
     * @return String the compressed IPv6-address (hex format)
     * @access public
     * @see    Uncompress()
     * @static
     * @author elfrink at introweb dot nl
     */
680
    public static function compress($ip, $force = false)
Ad Schellevis's avatar
Ad Schellevis committed
681
    {
682

Ad Schellevis's avatar
Ad Schellevis committed
683 684 685 686
        if(false !== strpos($ip, '::')) { // its already compressed

            if(true == $force) {

687
                $ip = Net_IPv6::uncompress($ip);
Ad Schellevis's avatar
Ad Schellevis committed
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768

            } else {

                return $ip;

            }

        }

        $prefix = Net_IPv6::getPrefixLength($ip);

        if (false === $prefix) {

            $prefix = '';

        } else {

            $ip     = Net_IPv6::removePrefixLength($ip);
            $prefix = '/'.$prefix;

        }

        $netmask = Net_IPv6::getNetmaskSpec($ip);
        $ip      = Net_IPv6::removeNetmaskSpec($ip);

        $ipp = explode(':', $ip);

        for ($i = 0; $i < count($ipp); $i++) {

            $ipp[$i] = dechex(hexdec($ipp[$i]));

        }

        $cip = ':' . join(':', $ipp) . ':';

        preg_match_all("/(:0)(:0)+/", $cip, $zeros);

        if (count($zeros[0]) > 0) {

            $match = '';

            foreach ($zeros[0] as $zero) {

                if (strlen($zero) > strlen($match)) {

                    $match = $zero;

                }
            }

            $cip = preg_replace('/' . $match . '/', ':', $cip, 1);

        }

        $cip = preg_replace('/((^:)|(:$))/', '', $cip);
        $cip = preg_replace('/((^:)|(:$))/', '::', $cip);

        if ('' != $netmask) {

            $cip = $cip.'/'.$netmask;

        }

        return $cip.$prefix;

    }

    // }}}
    // {{{ recommendedFormat()
    /**
     * Represent IPv6 address in RFC5952 format.
     *
     * @param String  $ip a valid IPv6-address (hex format)
     *
     * @return String the recommended representation of IPv6-address (hex format)
     * @access public
     * @see    compress()
     * @static
     * @author koyama at hoge dot org
     * @todo This method may become a part of compress() in a further releases
     */
769
    public static function recommendedFormat($ip)
Ad Schellevis's avatar
Ad Schellevis committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
    {
        $compressed = self::compress($ip, true);
        // RFC5952 4.2.2
        // The symbol "::" MUST NOT be used to shorten just one
        // 16-bit 0 field.
        if ((substr_count($compressed, ':') == 7) &&
            (strpos($compressed, '::') !== false)) {
            $compressed = str_replace('::', ':0:', $compressed);
        }
        return $compressed;
    }
    // }}}

    // {{{ isCompressible()

    /**
     * Checks, if an IPv6 address can be compressed
     *
     * @param String $ip a valid IPv6 address
789
     *
Ad Schellevis's avatar
Ad Schellevis committed
790
     * @return Boolean true, if address can be compressed
791
     *
Ad Schellevis's avatar
Ad Schellevis committed
792 793 794 795 796
     * @access public
     * @since 1.2.0b
     * @static
     * @author Manuel Schmitt
     */
797
    function isCompressible($ip)
Ad Schellevis's avatar
Ad Schellevis committed
798 799 800 801
    {

        return (bool)($ip != Net_IPv6::compress($address));

802
    }
Ad Schellevis's avatar
Ad Schellevis committed
803 804 805 806 807 808 809 810 811 812 813 814 815 816

    // }}}
    // {{{ SplitV64()

    /**
     * Splits an IPv6 address into the IPv6 and a possible IPv4 part
     *
     * RFC 2373 allows you to note the last two parts of an IPv6 address as
     * an IPv4 compatible address
     *
     * Example:  0:0:0:0:0:0:13.1.68.3
     *           0:0:0:0:0:FFFF:129.144.52.38
     *
     * @param String  $ip         a valid IPv6-address (hex format)
817
     * @param Boolean $uncompress if true, the address will be uncompressed
Ad Schellevis's avatar
Ad Schellevis committed
818 819 820 821 822 823 824
     *                            before processing
     *
     * @return Array  [0] contains the IPv6 part,
     *                [1] the IPv4 part (hex format)
     * @access public
     * @static
     */
825
    public static function SplitV64($ip, $uncompress = true)
Ad Schellevis's avatar
Ad Schellevis committed
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    {
        $ip = Net_IPv6::removeNetmaskSpec($ip);

        if ($uncompress) {

            $ip = Net_IPv6::Uncompress($ip);

        }

        if (strstr($ip, '.')) {

            $pos      = strrpos($ip, ':');
            $ip{$pos} = '_';
            $ipPart   = explode('_', $ip);

            return $ipPart;

        } else {

            return array($ip, "");

        }
    }

    // }}}
    // {{{ checkIPv6()

    /**
     * Checks an IPv6 address
     *
     * Checks if the given IP is IPv6-compatible
     *
     * @param String $ip a valid IPv6-address
     *
     * @return Boolean true if $ip is an IPv6 address
     * @access public
     * @static
     */
864
    public static function checkIPv6($ip)
Ad Schellevis's avatar
Ad Schellevis committed
865 866 867
    {

        $elements = Net_IPv6::separate($ip);
868

Ad Schellevis's avatar
Ad Schellevis committed
869 870 871 872 873 874
        $ip = $elements[0];

        if('' != $elements[1] && ( !is_numeric($elements[1]) || 0 > $elements[1] || 128 < $elements[1])) {

            return false;

875
        }
Ad Schellevis's avatar
Ad Schellevis committed
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891

        $ipPart = Net_IPv6::SplitV64($ip);
        $count  = 0;

        if (!empty($ipPart[0])) {
            $ipv6 = explode(':', $ipPart[0]);

            foreach($ipv6 as $element) { // made a validate precheck
                if(!preg_match('/[0-9a-fA-F]*/', $element)) {
                    return false;
                }
            }

            for ($i = 0; $i < count($ipv6); $i++) {

                if(4 < strlen($ipv6[$i])) {
892

Ad Schellevis's avatar
Ad Schellevis committed
893 894 895 896 897 898
                    return false;

                }

                $dec = hexdec($ipv6[$i]);
                $hex = strtoupper(preg_replace("/^[0]{1,3}(.*[0-9a-fA-F])$/",
899
                                                "\\1",
Ad Schellevis's avatar
Ad Schellevis committed
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
                                                $ipv6[$i]));

                if ($ipv6[$i] >= 0 && $dec <= 65535
                    && $hex == strtoupper(dechex($dec))) {

                    $count++;

                }

            }

            if (8 == $count) {

                return true;

            } else if (6 == $count and !empty($ipPart[1])) {

                $ipv4  = explode('.', $ipPart[1]);
                $count = 0;

                for ($i = 0; $i < count($ipv4); $i++) {

                    if ($ipv4[$i] >= 0 && (integer)$ipv4[$i] <= 255
                        && preg_match("/^\d{1,3}$/", $ipv4[$i])) {

                        $count++;

                    }

                }

                if (4 == $count) {

                    return true;

                }

            } else {

                return false;

            }

        } else {

            return false;

        }

    }

    // }}}

    // {{{ _parseAddress()

    /**
     * Returns the lowest and highest IPv6 address
     * for a given IP and netmask specification
958 959
     *
     * The netmask may be a part of the $ip or
Ad Schellevis's avatar
Ad Schellevis committed
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
     * the number of netmask bits is provided via $bits
     *
     * The result is an indexed array. The key 'start'
     * contains the lowest possible IP address. The key
     * 'end' the highest address.
     *
     * @param String $ipToParse the IPv6 address
     * @param String $bits      the optional count of netmask bits
     *
     * @return Array ['start', 'end'] the lowest and highest IPv6 address
     * @access public
     * @static
     * @author Nicholas Williams
     */

975
    public static function parseAddress($ipToParse, $bits = null)
Ad Schellevis's avatar
Ad Schellevis committed
976 977 978 979 980
    {

        $ip      = null;
        $bitmask = null;

981
        if ( null == $bits ) {
Ad Schellevis's avatar
Ad Schellevis committed
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

            $elements = explode('/', $ipToParse);

            if ( 2 == count($elements) ) {

                $ip      = Net_IPv6::uncompress($elements[0]);
                $bitmask = $elements[1];

            } else {

                include_once 'PEAR.inc';

                return PEAR::raiseError(NET_IPV6_NO_NETMASK_MSG,
                                        NET_IPV6_NO_NETMASK);
            }
        } else {

            $ip      = Net_IPv6::uncompress($ipToParse);
            $bitmask = $bits;

        }

        $binNetmask = str_repeat('1', $bitmask).
                      str_repeat('0', 128 - $bitmask);
        $maxNetmask = str_repeat('1', 128);
        $netmask    = Net_IPv6::_bin2Ip($binNetmask);

        $startAddress = Net_IPv6::_bin2Ip(Net_IPv6::_ip2Bin($ip)
                                          & $binNetmask);
        $endAddress   = Net_IPv6::_bin2Ip(Net_IPv6::_ip2Bin($ip)
                                          | ($binNetmask ^ $maxNetmask));

        return array('start' => $startAddress, 'end' => $endAddress);
    }

    // }}}

    // {{{ _ip2Bin()

    /**
     * Converts an IPv6 address from Hex into Binary representation.
     *
1024
     * @param String $ip the IP to convert (a:b:c:d:e:f:g:h),
Ad Schellevis's avatar
Ad Schellevis committed
1025 1026 1027 1028 1029 1030
     *                   compressed IPs are allowed
     *
     * @return String the binary representation
     * @access private
     @ @since 1.1.0
     */
1031
    protected static function _ip2Bin($ip)
Ad Schellevis's avatar
Ad Schellevis committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    {
        $binstr = '';

        $ip = Net_IPv6::removeNetmaskSpec($ip);
        $ip = Net_IPv6::Uncompress($ip);

        $parts = explode(':', $ip);

        foreach ( $parts as $v ) {

            $str     = base_convert($v, 16, 2);
            $binstr .= str_pad($str, 16, '0', STR_PAD_LEFT);

        }

        return $binstr;
    }

    // }}}
    // {{{ _bin2Ip()

    /**
     * Converts an IPv6 address from Binary into Hex representation.
     *
     * @param String $bin the IP address as binary
     *
     * @return String the uncompressed Hex representation
     * @access private
     @ @since 1.1.0
     */
1062
    protected static function _bin2Ip($bin)
Ad Schellevis's avatar
Ad Schellevis committed
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    {
        $ip = "";

        if (strlen($bin) < 128) {

            $bin = str_pad($bin, 128, '0', STR_PAD_LEFT);

        }

        $parts = str_split($bin, "16");

        foreach ( $parts as $v ) {

            $str = base_convert($v, 2, 16);
            $ip .= $str.":";

        }

        $ip = substr($ip, 0, -1);

        return $ip;
    }

    // }}}
}
// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */

?>