IP address subnet mask calculation

WBOY
Release: 2016-07-25 08:43:59
Original
2798 people have browsed it
IP address subnet mask calculation, returns IP segment starting and ending range, length, mask and other information.
  1. /**
  2. * Mask calculator
  3. * @author WeakSun <52132522@qq.com>
  4. * @param string $ip IP
  5. * @param numeric $bits mask
  6. * @return array Return the result set
  7. */
  8. function netmask($ip, $bits = 24) {
  9. $result = [
  10. 'start' => 0, //First IP
  11. 'end' = > 0, //The last IP
  12. 'length' => 0, //The number of IPs included
  13. 'netmask' => (~pow(2, 32 - $bits)) + 1, //Sub Netmask
  14. 'networkSegment' => 0, //IP segment
  15. 'bcast' => 0//Broadcast address
  16. ];
  17. $result['length'] = abs($result['netmask']) - 2;
  18. $result['networkSegment'] = ip2long($ip) & $result['netmask'];
  19. $result['start'] = $result['networkSegment'] + 1;
  20. $result[' end'] = $result['networkSegment'] + $result['length'];
  21. $result['bcast'] = $result['end'] + 1;
  22. return $result;
  23. }
Copy Code
  1. list($ip, $bits) = explode('/', '192.168.1.5/25');
  2. $tmpArr = netmask($ip, $bits);
  3. foreach ($tmpArr as $k = > &$v) {
  4. $k != 'length' && $v = long2ip($v);
  5. }
  6. echo '
    ' . var_export($tmpArr, true).'
    ';
Copy code
  1. 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
Subnet mask


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template