ipaddresses::netmask2cidr : manage the calculation of the wildcard IP

ipaddresses::netmask2cidr : catch invalid IP mask and return false


git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@5987 bf3deb0d-5f1a-0410-827f-c0cc1f45334c
This commit is contained in:
2020-05-11 19:39:20 +00:00
parent e1f1ddaa24
commit 068b1e3ec3
2 changed files with 51 additions and 6 deletions

View File

@@ -363,6 +363,32 @@ class ipaddressesTest extends PHPUnit_Framework_TestCase
$res = $i->netmask2cidr ("63.0.0.0");
$this->assertSame (6, $res);
}
public function test_netmask2cidr8 ()
{
$i = new ipaddresses ();
$res = $i->netmask2cidr ("155.0.0.0");
$this->assertSame (false, $res);
}
public function test_netmask2cidrWildcard_1 ()
{
$i = new ipaddresses ();
$res = $i->netmask2cidr ("255.255.255.0", false);
$this->assertSame (false, $res);
}
public function test_netmask2cidrWildcard_2 ()
{
$i = new ipaddresses ();
$res = $i->netmask2cidr ("0.0.0.0", false);
$this->assertSame (32, $res);
}
public function test_netmask2cidrWildcard_3 ()
{
$i = new ipaddresses ();
$res = $i->netmask2cidr ("255.255.255.255", false);
$this->assertSame (0, $res);
}
public function test_ipInNetwork1 ()
{

View File

@@ -476,26 +476,45 @@ class ipaddresses
// }}}
/** This function return the CIDR associated to the provided netmask
* Ex. Return 24 for a mask 255.255.255.0
* Ex. Return 24 for a mask 255.255.255.0 in direct
* Ex. Return 24 for a mask 0.0.0.255 in wildcard
* Work only in IPv4
* Return FALSE if the provided IP is invalid
* Return FALSE if the provided mask is invalid (155.0.0.0 by example)
* Throw an exception if the provided IP is invalid
* @param string $netmask The mask to convert in CIDR
* @param boolean|null $maskdirect If true check a direct mask, if false
* check a wildcard mask
*/
public function netmask2cidr ($netmask)
public function netmask2cidr ($netmask, $maskdirect = true)
// {{{
{
$maskdirect = "". ($maskdirect + 0);
$maskrevert = ($maskdirect === "0") ? "1" : "0";
$netmask = ip2long ($netmask);
if ($netmask === FALSE)
throw new \Exception (dgettext ("domframework", "Invalid netmask"), 500);
$netmask = decbin ($netmask);
for ($i=0 ; $i<32 ; $i++)
$res = -1;
for ($i = 0 ; $i < 32 ; $i++)
{
if ($netmask{$i} == 0)
if (! isset ($netmask[$i]))
{
break;
}
elseif ($res == -1 && $netmask[$i] === $maskrevert)
{
$res = $i;
}
elseif ($res !== -1 && $netmask[$i] === $maskdirect)
{
return false;
}
}
return $i;
if ($res === -1 && $i === 32)
return 32;
if ($res === -1 && $i === 1)
return 32;
return $res;
}
// }}}