1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JAAulde\IP\V4; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Represents an IP(V4) subnet mask. |
7
|
|
|
* |
8
|
|
|
* @author Jim Auldridge <[email protected]> |
9
|
|
|
* @copyright 2006-2015 Jim Auldridge |
10
|
|
|
* @license MIT |
11
|
|
|
*/ |
12
|
|
|
class SubnetMask extends Address |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Retrieve the number of host bits denoted by this mask. |
16
|
|
|
* |
17
|
|
|
* @return int |
18
|
|
|
*/ |
19
|
|
|
public function getHostBitsCount() |
20
|
|
|
{ |
21
|
|
|
return 32 - $this->getNetworkBitsCount(); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Retrieve the number of network bits denoted by this mask. |
26
|
|
|
* |
27
|
|
|
* @return int |
28
|
|
|
*/ |
29
|
|
|
public function getNetworkBitsCount() |
30
|
|
|
{ |
31
|
|
|
return (int) (32 - log(($this->get() ^ ip2long('255.255.255.255')) + 1, 2)); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Alias to \JAAulde\IP\V4\SubnetMask::getNetworkBitsCount. |
36
|
|
|
* |
37
|
|
|
* @uses \JAAulde\IP\V4\SubnetMask::getNetworkBitsCount |
38
|
|
|
* |
39
|
|
|
* @return int |
40
|
|
|
*/ |
41
|
|
|
public function getCIDRPrefix() |
42
|
|
|
{ |
43
|
|
|
return $this->getNetworkBitsCount(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Given two (2) IP (V4) addresses, calculate a CIDR prefix for the network which could contain them both. |
48
|
|
|
* |
49
|
|
|
* @param \JAAulde\IP\V4\Address $address1 |
50
|
|
|
* @param \JAAulde\IP\V4\Address $address2 |
51
|
|
|
*/ |
52
|
|
|
public static function calculateCIDRToFit(Address $address1, Address $address2) |
53
|
|
|
{ |
54
|
|
|
return (int) floor(32 - log(($address1->get() ^ $address2->get()) + 1, 2)); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Factory method for producing a SubnetMask instance from a CIDR (slash notation) prefix size. |
59
|
|
|
* |
60
|
|
|
* @param int $prefixSize Number of network bits to be represented by the subnet mask |
61
|
|
|
* |
62
|
|
|
* @return self |
63
|
|
|
* |
64
|
|
|
* @throws Exception |
65
|
|
|
*/ |
66
|
|
|
public static function fromCIDRPrefix($prefixSize) |
67
|
|
|
{ |
68
|
|
|
if (!is_int($prefixSize)) { |
69
|
|
|
throw new \Exception(__METHOD__.' requires first param, $prefixSize, to be an integer'); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if ($prefixSize < 1 || $prefixSize > 31) { |
73
|
|
|
throw new \Exception(__METHOD__.' requires first param, $prefixSize, to be CIDR prefix size with value between 1 and 31 (inclusive)'); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return new self(bindec(str_repeat('1', $prefixSize).str_repeat('0', 32 - $prefixSize))); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|