From e49fcfa0c7b4933b076baf6ee2b8ca18d744fbc0 Mon Sep 17 00:00:00 2001 From: Shish Date: Thu, 4 Jan 2024 15:07:07 +0000 Subject: [PATCH] [core] allow ip_in_range to match exact IPs --- core/polyfills.php | 6 +++++- core/tests/PolyfillsTest.php | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/core/polyfills.php b/core/polyfills.php index 6609945d..0e6f6afd 100644 --- a/core/polyfills.php +++ b/core/polyfills.php @@ -36,7 +36,11 @@ function array_iunique(array $array): array */ function ip_in_range(string $IP, string $CIDR): bool { - list($net, $mask) = explode("/", $CIDR); + $parts = explode("/", $CIDR); + if(count($parts) == 1) { + $parts[1] = "32"; + } + list($net, $mask) = $parts; $ip_net = ip2long($net); $ip_mask = ~((1 << (32 - (int)$mask)) - 1); diff --git a/core/tests/PolyfillsTest.php b/core/tests/PolyfillsTest.php index 649ca68a..f8e023f0 100644 --- a/core/tests/PolyfillsTest.php +++ b/core/tests/PolyfillsTest.php @@ -226,4 +226,13 @@ class PolyfillsTest extends TestCase stringer(["foo" => "bar", "baz" => [1,2,3], "qux" => ["a" => "b"]]) ); } + + public function test_ip_in_range() + { + $this->assertTrue(ip_in_range("1.2.3.4", "1.2.0.0/16")); + $this->assertFalse(ip_in_range("4.3.2.1", "1.2.0.0/16")); + + // A single IP should be interpreted as a /32 + $this->assertTrue(ip_in_range("1.2.3.4", "1.2.3.4")); + } }