ipaddresses : Add cidr2netmask method for IPv4 masks
git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@5989 bf3deb0d-5f1a-0410-827f-c0cc1f45334c
This commit is contained in:
@@ -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 ();
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user