我将使用以下URL来编写我需要的函数:
http://www.zytrax.com/tech/protocols/ipv6.html
我将用函数代码进行编辑。
编辑
希望人们能发现这一点。
class Connect {
/**
* Returns the IP in it's fullest format.
* @example
* ::1 => 0000:0000:0000:0000:0000:0000:0000:0001
* 220F::127.0.0.1 => 220F:0000:0000:0000:0000:0000:7F00:0001
* 2F:A1::1 => 002F:00A1:0000:0000:0000:0000:0000:0001
* @param string $ip Original/compressed/packed IPv6.
* @return string Full IP.
*/
protected static function fixIpv6($ip){
// fix double colon
if(strpos($ip,'::')!==false)$ip=str_replace('::',str_repeat(':',9-substr_count($ip,':')),$ip);
// fix each slot
$ip=explode(':',$ip);
foreach($ip as $k=>$v){
// fix empty/compressed slots
$ip[$k]=$v=str_pad($v,4,'0',STR_PAD_LEFT);
// fix ipv4-style slot
if(strpos($v,'.')!==false){
// initially empty buffer
$ip[$k]='';
// replace each number(byte) with a two-digit hex representation
foreach(explode('.',$v) as $v2){
$v=dechex(min((int)$v2,255));
if(strlen($v)==1)$v='0'.$v;
$ip[$k].=$v;
}
// add colon in between two pairs(bytes) (FFFFFFFF=>FFFF:FFFF)
$ip[$k]=implode(':',str_split($ip[$k],4));
}
}
return strtoupper(implode(':',$ip));
}
/**
* Compresses an IP to it's binary representation.
* @param string $ip A well-formatted full IPv4 or IPv6 address.
* @return string Binary representation of address.
*/
public static function compressIp($ip){
if(strpos($ip,':')!==false){ // ipv6
$ip=str_split(str_replace(':','',self::fixIpv6($ip)),2);
foreach($ip as $k=>$v)$ip[$k]=chr(hexdec($v));
return implode('',$ip);
}elseif(strpos($ip,'.')!==false){ // ipv4
$ip=explode('.',$ip);
if(count($ip)!=4)$ip=array(0,0,0,0);
return chr($ip[0]).chr($ip[1]).chr($ip[2]).chr($ip[3]);
}else throw new Exception('Unrecognized IP format: '.MB_SECURITY::snohtml($ip));
}
}