46 lines
1.1 KiB
PHP
46 lines
1.1 KiB
PHP
<?php
|
|
|
|
class IPv4Subnet
|
|
{
|
|
|
|
private string $address;
|
|
private int $prefix;
|
|
|
|
/**
|
|
* @param string $subnetAddress
|
|
* @param int $prefix
|
|
*/
|
|
public function __construct(string $subnetAddress, int $prefix)
|
|
{
|
|
$this->address = $subnetAddress;
|
|
if (ip2long($subnetAddress) === false) {
|
|
throw new RuntimeException("Invalid subnet address: " . $subnetAddress);
|
|
}
|
|
$this->prefix = $prefix;
|
|
if ($prefix < 0 or $prefix > 32) {
|
|
throw new RuntimeException("Invalid subnet prefix: " . $prefix);
|
|
}
|
|
}
|
|
|
|
public function getFirstAddress()
|
|
{
|
|
$a = ip2long($this->address);
|
|
$mask = ip2long($this->getNetMask());
|
|
return long2ip($a & $mask);
|
|
}
|
|
|
|
public function getLastAddress()
|
|
{
|
|
return long2ip(ip2long($this->getFirstAddress()) + $this->getAddressCount() - 1);
|
|
}
|
|
|
|
public function getAddressCount()
|
|
{
|
|
return pow(2, 32 - $this->prefix);
|
|
}
|
|
|
|
public function getNetMask()
|
|
{
|
|
return long2ip(-1 << (32 - $this->prefix));
|
|
}
|
|
} |