Heim  >  Artikel  >  Backend-Entwicklung  >  php实现IP地址转换为整型数字实例_PHP教程

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

PHP中文网
PHP中文网Original
2016-07-13 16:57:38898Durchsuche

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);
 }

http://www.bkjia.com/PHPjc/631516.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631516.htmlTechArticleIP地址转换在整型数据然后保存到数据库中,这是一种常用的做法,我们转换IP地算法是intIP = 256*256*256*w + 256*256*x + 256*y + z即可,下面来给各...


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn