From 054da30ba9eff11b6beb065dd42dfe7ee1b8003b Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Fri, 5 Feb 2016 14:56:01 +0000 Subject: [PATCH] MDL-48766 moodlelib: introduce ip_is_public() For determining if an IP is publicly addressable --- lib/moodlelib.php | 13 ++++++++-- lib/tests/moodlelib_test.php | 48 ++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/lib/moodlelib.php b/lib/moodlelib.php index fc0fc312a2e..0977ec1b16b 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -8641,8 +8641,6 @@ function getremoteaddr($default='0.0.0.0') { function cleanremoteaddr($addr, $compress=false) { $addr = trim($addr); - // TODO: maybe add a separate function is_addr_public() or something like this. - if (strpos($addr, ':') !== false) { // Can be only IPv6. $parts = explode(':', $addr); @@ -8735,6 +8733,17 @@ function cleanremoteaddr($addr, $compress=false) { return implode('.', $parts); } + +/** + * Is IP address a public address? + * + * @param string $ip The ip to check + * @return bool true if the ip is public + */ +function ip_is_public($ip) { + return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)); +} + /** * This function will make a complete copy of anything it's given, * regardless of whether it's an object or not. diff --git a/lib/tests/moodlelib_test.php b/lib/tests/moodlelib_test.php index 353187e7225..d9c53fc0187 100644 --- a/lib/tests/moodlelib_test.php +++ b/lib/tests/moodlelib_test.php @@ -3130,4 +3130,52 @@ class core_moodlelib_testcase extends advanced_testcase { $this->assertSame('', $result); $this->assertDebuggingCalled(); } + + /** + * Data provider for private ips. + */ + public function data_private_ips() { + return array( + array('10.0.0.0'), + array('172.16.0.0'), + array('192.168.1.0'), + array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'), + array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'), + array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'), + array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150. + ); + } + + /** + * Checks ip_is_public returns false for private ips. + * + * @param string $ip the ipaddress to test + * @dataProvider data_private_ips + */ + public function test_ip_is_public_private_ips($ip) { + $this->assertFalse(ip_is_public($ip)); + } + + /** + * Data provider for public ips. + */ + public function data_public_ips() { + return array( + array('2400:cb00:2048:1::8d65:71b3'), + array('2400:6180:0:d0::1b:2001'), + array('141.101.113.179'), + array('123.45.67.178'), + ); + } + + /** + * Checks ip_is_public returns true for public ips. + * + * @param string $ip the ipaddress to test + * @dataProvider data_public_ips + */ + public function test_ip_is_public_public_ips($ip) { + $this->assertTrue(ip_is_public($ip)); + } + } -- 2.43.0