IpUtilsTest.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Tests;
  11. use Symfony\Component\HttpFoundation\IpUtils;
  12. class IpUtilsTest extends \PHPUnit_Framework_TestCase
  13. {
  14. /**
  15. * @dataProvider testIpv4Provider
  16. */
  17. public function testIpv4($matches, $remoteAddr, $cidr)
  18. {
  19. $this->assertSame($matches, IpUtils::checkIp($remoteAddr, $cidr));
  20. }
  21. public function testIpv4Provider()
  22. {
  23. return array(
  24. array(true, '192.168.1.1', '192.168.1.1'),
  25. array(true, '192.168.1.1', '192.168.1.1/1'),
  26. array(true, '192.168.1.1', '192.168.1.0/24'),
  27. array(false, '192.168.1.1', '1.2.3.4/1'),
  28. array(false, '192.168.1.1', '192.168.1/33'),
  29. array(true, '192.168.1.1', array('1.2.3.4/1', '192.168.1.0/24')),
  30. array(true, '192.168.1.1', array('192.168.1.0/24', '1.2.3.4/1')),
  31. array(false, '192.168.1.1', array('1.2.3.4/1', '4.3.2.1/1')),
  32. );
  33. }
  34. /**
  35. * @dataProvider testIpv6Provider
  36. */
  37. public function testIpv6($matches, $remoteAddr, $cidr)
  38. {
  39. if (!defined('AF_INET6')) {
  40. $this->markTestSkipped('Only works when PHP is compiled without the option "disable-ipv6".');
  41. }
  42. $this->assertSame($matches, IpUtils::checkIp($remoteAddr, $cidr));
  43. }
  44. public function testIpv6Provider()
  45. {
  46. return array(
  47. array(true, '2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'),
  48. array(false, '2a00:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'),
  49. array(false, '2a01:198:603:0:396e:4789:8e99:890f', '::1'),
  50. array(true, '0:0:0:0:0:0:0:1', '::1'),
  51. array(false, '0:0:603:0:396e:4789:8e99:0001', '::1'),
  52. array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '2a01:198:603:0::/65')),
  53. array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('2a01:198:603:0::/65', '::1')),
  54. array(false, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '1a01:198:603:0::/65')),
  55. );
  56. }
  57. /**
  58. * @expectedException \RuntimeException
  59. */
  60. public function testAnIpv6WithOptionDisabledIpv6()
  61. {
  62. if (!extension_loaded('sockets')) {
  63. $this->markTestSkipped('Only works when the socket extension is enabled');
  64. }
  65. if (defined('AF_INET6')) {
  66. $this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".');
  67. }
  68. IpUtils::checkIp('2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65');
  69. }
  70. }