Skip to content

Commit

Permalink
Allow netmask to be specified when initializing IPv4 networks instead…
Browse files Browse the repository at this point in the history
… of cidr.
  • Loading branch information
murrant committed May 16, 2018
1 parent defdae3 commit 1396492
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
23 changes: 23 additions & 0 deletions LibreNMS/Util/IPv4.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,27 @@ public function toSnmpIndex()
{
return (string)$this->ip;
}

/**
* Extract an address from a cidr, assume a host is given if it does not contain /
* Handle netmasks in addition to cidr
*
* @param string $ip
* @return array [$ip, $cidr]
*/
protected function extractCidr($ip)
{
$parts = explode('/', $ip, 2);

if (isset($parts[1])) {
if (strpos($parts[1], '.') !== false) {
// could be a netmask instead of cidr
$parts[1] = self::netmask2cidr($parts[1]);
}
} else {
$parts[1] = $this->host_bits;
}

return $parts;
}
}
6 changes: 6 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<phpunit colors="true" strict="true" bootstrap="vendor/autoload.php">
<testsuite name='ip-utils tests'>
<directory suffix='.php'>tests</directory>
</testsuite>
</phpunit>
11 changes: 11 additions & 0 deletions tests/IpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,16 @@ public function testIpParse()
$this->assertEquals('::1', new IPv6('::1'));
}

public function testNetworkParse()
{
$this->assertEquals('192.168.3.0/24', IP::parse('192.168.3.0/24'));
$this->assertEquals('192.168.0.1', IP::parse('192.168.0.1/32'));
$this->assertEquals('127.0.0.1/8', IP::parse('127.0.0.1/8'));
$this->assertEquals('10.8.0.0/22', IP::parse('10.8.0.0/255.255.252.0'));
$this->assertEquals('2001:db8:85a3::8a2e:370:7334/64', IP::parse('2001:db8:85a3::8a2e:370:7334/64'));
$this->assertEquals('::1', IP::parse('::1/128'));
}

/**
* @expectedException \LibreNMS\Exceptions\InvalidIpException
*/
Expand Down Expand Up @@ -155,6 +165,7 @@ public function testNetmask2Cidr()
$this->assertSame(30, IPv4::netmask2cidr('255.255.255.252'));
$this->assertSame(26, IPv4::netmask2cidr('255.255.255.192'));
$this->assertSame(16, IPv4::netmask2cidr('255.255.0.0'));
$this->assertSame(0, IPv4::netmask2cidr('0.0.0.0'));
}

/**
Expand Down

0 comments on commit 1396492

Please sign in to comment.