【學習點滴-php】php ipv4常用功能封裝

來源:互聯網
上載者:User
<?php/** * @author :xiaoqing.huo * @date   :2012-12-05 * @param  :$ip==>ipv4 address,$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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.