现在的位置: 首页 > 综合 > 正文

【学习点滴-php】php ipv4常用功能封装

2013年09月03日 ⁄ 综合 ⁄ 共 1477字 ⁄ 字号 评论关闭
<?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;

抱歉!评论已关闭.