php IP conversion plastic of ip2long details

  • 2020-06-07 04:06:10
  • OfStack

How do I convert the four IP network Address protocol addresses, which are dotted apart, to integers? So PHP has this function ip2long, for example


<?php
echo ip2long("10.2.1.3");
?>

We're going to get
167903491

How does this work? So far I know there are two algorithms. Its 1

<?php
function ip2int($ip){
   // Let's put the ip Divided into 4 Period of ,$ip1,$ip2,$ip3,$ip4
   list($ip1,$ip2,$ip3,$ip4)=explode(".",$ip);
   // Then the first 1 Period of times 256 the 3 The power, the first 2 Period of times 256 Omega squared, omega squared 3 Period of times 256
   // That's what we get 
    return$ip1*pow(256,3)+$ip2*pow(256,2)+$ip3*256+$ip4;
}
?>

And then the two, we're going to use bits

<?php
function ip2int($ip){
   list($ip1,$ip2,$ip3,$ip4)=explode(".",$ip);
    return($ip1<<24)|($ip2<<16)|($ip3<<8)|($ip4);
}
?>

We will find that some ip converted to integers is negative because the result is a signed integer with a maximum value of 2147483647
sprintf("%u",ip2long($ip);

I can convert it to a positive integer. Moreover, the results obtained by using long2ip can be normally converted back to the original ip address. ip2long can also be used to verify whether 1 ip is valid, such as


<?php
function chk_ip($ip){
   if(ip2long($ip)=="-1") {
      return false;
    }
    returntrue;
}
// application 
var_export(chk_ip("10.111.149.42"));
var_export(chk_ip("10.111.256.42"));
?>

true and false will be output

The ip data stored in the database (MySQL) in time, we use ip2long function to generate integer, and then stored in a int (11) types of fields, however, in the different system platforms, ip2long function value is different, so may cause in the read data from a database, using long2ip get ip errors, said 1: we met
We used an int(11) type (range -2147483648) -2147483647) to save the result of processing an ip address with ip2long, for example, ip is '202.105.77.179 ', then the result on the 32-bit machine is :-899068493 and on the 64-bit machine is 3395898803. Then it is written to the database, as it exceeds the range of int(11), so the result on the 64-bit machine is saved as the maximum value of int(11) :2147483647 When you pull it out, you get the wrong result. You get the ip address of "127.255.255.255".
There are many solutions. For example, you can use mysql's functions :INET_ATON and INET_NTOA to handle ip addresses. Or change the field that holds the ip address to type bigint, so that on a 64-bit machine you can still get the correct result using the long2ip function, even though you are saving 3395898803.


Related articles: