【PHP】php ipv4常用功能封装

来源:互联网 发布:java培训机构都有哪些 编辑:程序博客网 时间:2024/06/05 18:18
<?php/** * @date   :2012-12-05 * @param  :ip ==> ipv4 address, * @param  :netBit ==> mask bits */class IpConfigure{private $ip;private $netBit;public function __construct($ip,$netBit){$this->ip = $ip;if(!($netBit>=0 && $netBit<=32)){$this->netBit = 32;}$this->netBit = $netBit;}//获取网络号public function getSubnet(){return (long2ip((ip2long($this->ip)) & (ip2long($this->getMask()))));}//获取ip地址public function getIp(){return $this->ip;}//获取掩码位数public function getNetBit(){return $this->netBit;}//获取子网掩码public function getMask(){$maskBinStr =str_repeat("1", $this->netBit ) . str_repeat("0", 32-$this->netBit );$maskLong = bindec($maskBinStr);return long2ip($maskLong);}//获取可用网络段,返回开始和结束ip地址public function getIpRange(){$maskBinStr =str_repeat("1", $this->netBit ) . str_repeat("0", 32-$this->netBit );      //net mask binary string$inverseMaskBinStr = str_repeat("0", $this->netBit ) . str_repeat("1",  32-$this->netBit ); //inverse mask  $ipLong = ip2long( $this->ip );$ipMaskLong = bindec( $maskBinStr );$inverseIpMaskLong = bindec( $inverseMaskBinStr );$netWork = $ipLong & $ipMaskLong; $start = $netWork + 1;//去掉网络号 ,主机地址为全0的地址 $end = ($netWork | $inverseIpMaskLong) -1 ; //去掉广播地址,即主机地址全1的地址return array( long2ip($start), long2ip($end) );}//获取广播地址public  function broadcast(){return (long2ip(ip2long($this->getSubnet()) | (~(ip2long($this->getMask())))));}}$configure = new IpConfigure("10.31.144.0",22);echo "网络号:",$configure->getSubnet().PHP_EOL;echo "<pre>";echo "可用网段:";print_r($configure->getIpRange());echo "子网掩码:",$configure->getMask().PHP_EOL;echo "广播地址:",$configure->broadcast().PHP_EOL;