From cf4c92b7bff94e4aad842099a6c2387a8510c036 Mon Sep 17 00:00:00 2001 From: Dominique Fournier Date: Mon, 11 May 2020 20:29:13 +0000 Subject: [PATCH] ipaddresses : Add cidr2netmask method for IPv4 masks git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@5989 bf3deb0d-5f1a-0410-827f-c0cc1f45334c --- Tests/ipaddressesTest.php | 34 ++++++++++++++++++++++++++++++++++ ipaddresses.php | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/Tests/ipaddressesTest.php b/Tests/ipaddressesTest.php index d72fded..40b370b 100644 --- a/Tests/ipaddressesTest.php +++ b/Tests/ipaddressesTest.php @@ -396,6 +396,40 @@ class ipaddressesTest extends PHPUnit_Framework_TestCase $this->assertSame (0, $res); } + public function test_cidr2netmask_1 () + { + $i = new ipaddresses (); + $res = $i->cidr2netmask (0, true); + $this->assertSame ("0.0.0.0", $res); + } + + public function test_cidr2netmask_2 () + { + $i = new ipaddresses (); + $res = $i->cidr2netmask (24, true); + $this->assertSame ("255.255.255.0", $res); + } + + public function test_cidr2netmask_3 () + { + $i = new ipaddresses (); + $res = $i->cidr2netmask (25, true); + $this->assertSame ("255.255.255.128", $res); + } + + public function test_cidr2netmask_4 () + { + $i = new ipaddresses (); + $res = $i->cidr2netmask (32, true); + $this->assertSame ("255.255.255.255", $res); + } + public function test_cidr2netmask_5 () + { + $i = new ipaddresses (); + $res = $i->cidr2netmask (1, true); + $this->assertSame ("128.0.0.0", $res); + } + public function test_ipInNetwork1 () { $i = new ipaddresses (); diff --git a/ipaddresses.php b/ipaddresses.php index c6ca209..9482f24 100644 --- a/ipaddresses.php +++ b/ipaddresses.php @@ -521,6 +521,41 @@ class ipaddresses } // }}} + /** This function return the netmask associated to a CIDR. + * Work only on IPv4 addresses (CIDR between 0 and 32) + * @param string $cidr The CIDR to convert in netmask + * @param boolean|null $maskdirect If true return a direct mask, if false + * return a wildcard mask + * @return the mask + * @return false if the CIDR is not between 0 and 32 + */ + public function cidr2netmask ($cidr, $maskdirect = true) + // {{{ + { + if ($cidr < 0 || $cidr > 32) + return false; + $maskdirect = "". ($maskdirect + 0); + $maskrevert = ($maskdirect === "0") ? "1" : "0"; + $bin = ""; + for ($i = 0 ; $i < 32 ; $i++) + { + if ($i < $cidr) + $bin .= $maskdirect; + else + $bin .= $maskrevert; + } + $res = ""; + for ($i = 0 ; $i < 32 ; $i = $i + 8) + { + $block = substr ($bin, $i, 8); + if ($i > 0) + $res .= "."; + $res .= bindec ($block); + } + return $res; + } + // }}} + /** This function return true if the provided address is in the provided * network with the associated cidr * @param string $ip The IPv4 or IPv6 to test