当前位置:Gxlcms > PHP教程 > IP地址子网掩码计算

IP地址子网掩码计算

时间:2021-07-01 10:21:17 帮助过:9人阅读

IP地址子网掩码计算,返回IP段起止范围、长度、掩码等信息。
  1. /**
  2. * 掩码计算器
  3. * @author WeakSun <52132522@qq.com>
  4. * @param string $ip IP
  5. * @param numeric $bits 掩码
  6. * @return array 返回结果集
  7. */
  8. function netmask($ip, $bits = 24) {
  9. $result = [
  10. 'start' => 0, //第一个IP
  11. 'end' => 0, //最后一个IP
  12. 'length' => 0, //包含的IP个数
  13. 'netmask' => (~pow(2, 32 - $bits)) + 1, //子网掩码
  14. 'networkSegment' => 0, //IP段
  15. 'bcast' => 0//广播地址
  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. }
  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).'
    ';
  1. array (
  2. 'start' => '192.168.1.1',
  3. 'end' => '192.168.1.126',
  4. 'length' => 126,
  5. 'netmask' => '255.255.255.128',
  6. 'networkSegment' => '192.168.1.0',
  7. 'bcast' => '192.168.1.127',
  8. )
子网掩码

人气教程排行