Example of converting IP address to integer number in PHP_PHP tutorial

PHP中文网
Release: 2016-07-13 16:57:38
Original
891 people have browsed it

The IP address is converted into integer data and then saved in the database. This is a common practice. Our algorithm for converting IP is intIP = 256*256*256*w + 256*256*x + 256*y + z is enough. Let me introduce specific examples to you.

[Conversion principle]: Assuming that the IP is: w.x.y.z, the calculation formula for converting the IP address into an integer number is: intIP = 256*256*256*w + 256*256*x + 256*y + z

[PHP conversion]: PHP conversion method is relatively simple, it has two built-in functions

int ip2long ( string $ip_address ) //ip conversion Integer value
string long2ip ( string $proper_address ) // Convert integer value to ip [MySQL conversion]: Compared with MsSQL, MySQL's conversion method is relatively simple, and it is similar to PHP There are also two built-in functions

IP to integer:

select INET_ATON (IP address) integer value converted to IP

select INET_NTOA (IP integer Value)


An instance

  1. Manual implementation method

 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

http://www .bkjia.com/PHPjc/631516.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631516.htmlTechArticleIP address is converted into integer data and then saved to the database. This is a common practice, we convert The IP algorithm is intIP = 256*256*256*w + 256*256*x + 256*y + z. Let’s give each...


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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!