IP address subnet mask calculation, returns IP segment starting and ending range, length, mask and other information.
- /**
- * Mask calculator
- * @author WeakSun <52132522@qq.com>
- * @param string $ip IP
- * @param numeric $bits mask
- * @return array Return the result set
- */
- function netmask($ip, $bits = 24) {
- $result = [
- 'start' => 0, //First IP
- 'end' = > 0, //The last IP
- 'length' => 0, //The number of IPs included
- 'netmask' => (~pow(2, 32 - $bits)) + 1, //Sub Netmask
- 'networkSegment' => 0, //IP segment
- 'bcast' => 0//Broadcast address
- ];
- $result['length'] = abs($result['netmask']) - 2;
- $result['networkSegment'] = ip2long($ip) & $result['netmask'];
- $result['start'] = $result['networkSegment'] + 1;
- $result[' end'] = $result['networkSegment'] + $result['length'];
- $result['bcast'] = $result['end'] + 1;
- return $result;
- }
Copy Code
- list($ip, $bits) = explode('/', '192.168.1.5/25');
- $tmpArr = netmask($ip, $bits);
- foreach ($tmpArr as $k = > &$v) {
- $k != 'length' && $v = long2ip($v);
- }
- echo '
' . var_export($tmpArr, true).' ';
Copy code
array (</li>
<li> 'start' => '192.168.1.1',</li>
<li> 'end' => '192.168.1.126',</li>
<li> 'length' => 126,</li>
<li> 'netmask' = > '255.255.255.128',</li>
<li> 'networkSegment' => '192.168.1.0',</li>
<li> 'bcast' => '192.168.1.127',</li>
<li>)
Copy code
|