Home > php教程 > php手册 > php实现IP地址转换为整型数字实例

php实现IP地址转换为整型数字实例

PHP中文网
Release: 2016-05-25 16:54:42
Original
1310 people have browsed it

IP地址转换在整型数据然后保存到数据库中,这是一种常用的做法,我们转换IP地算法是intIP = 256*256*256*w + 256*256*x + 

256*y + z即可,下面来给各位同学介绍具体实例。

【转换原理】:假设IP为:w.x.y.z,则IP地址转为整型数字的计算公式为:intIP = 256*256*256*w + 256*256*x + 256*y + z

【PHP的互转】:PHP的转换方式比较简单,它内置了两个函数

int ip2long ( string $ip_address ) //ip转换成整型数值
string long2ip ( string $proper_address ) // 整型数值转换成ip【MySQL的互转】:相对于MsSQL来说MySQL的转换方式比较简单,它和PHP一样也内置了两个函数

IP 转为整型:

select INET_ATON (IP地址)整型数值转换成IP

select INET_NTOA ( IP的整型数值 )


一个实例

1.手工自己的实现方法

function ip2number($ip)
      {
          $t = explode('.', $ip);
          $x = 0;
          for ($i = 0; $i < 4; $i++)
          {
              $x = $x * 256 + $t[$i];
          }
          return $x;
      }
function number2ip($num)
      {
          $t = $num;
          $a = array();
          for ($i = 0; $i < 4; $i++)
          {
              $x = $t % 256;
              if($x < 0) $x += 256;
              array_unshift($a, $x);
              $t = intval($t / 256);
          }
          return implode(&#39;.&#39;, $a);
 }
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template