我们将得到  "/>   我们将得到  ">

Home  >  Article  >  Backend Development  >  PHP:IP变换整形(转)

PHP:IP变换整形(转)

WBOY
WBOYOriginal
2016-06-13 12:34:561032browse

PHP:IP转换整形(转)

本文转载自:?? http://blog.chinaunix.net/uid-10697776-id-2935481.html

?

?

?

如何将四个字段以点分开的IP网络址协议地址转换成整数呢?PHP里有这么一个函数ip2long.比如

echoip2long("10.2.1.3");<br>?>

  我们将得到

  167903491

  这是如何计算的,目前我知道有两个算法。其一

functionip2int($ip){<br> //我们先把ip分为四段,$ip1,$ip2,$ip3,$ip4<br> list($ip1,$ip2,$ip3,$ip4)=explode(".",$ip);<br> //然后第一段乘以256的三次方,第二段乘以256的平方,第三段乘以256<br> //这即是我们得到的值<br> return$ip1*pow(256,3)+$ip2*pow(256,2)+$ip3*256+$ip4;<br>}<br>?>

  其二,用位运算

functionip2int($ip){<br> list($ip1,$ip2,$ip3,$ip4)=explode(".",$ip);<br> return($ip1}<br>?>

  我们会发现,有些ip转化成整数后,是负的,这是因为得到的结果是有符号整型,最大值是2147483647.要把它转化为无符号的,可以用

  sprintf("%u",ip2long($ip);

  就能转换为正整数。而且得到的结果用long2ip也可以正常转换回原来的ip地址。也可以用ip2long来验证一个ip是否是有效的,如

functionchk_ip($ip){<br> if(ip2long($ip)=="-1"){<br>   returnfalse;<br> }<br> returntrue;<br>}<br>//应用<br>var_export(chk_ip("10.111.149.42"));<br>var_export(chk_ip("10.111.256.42"));<br>?>

  将输出true和false

?

?

?

?

?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn