PHP: IP address conversion (convert) This article is reproduced from :?? Http://blog.chinaunix.net/uid-10697776-id-2935481.html ??? How can we convert IP address protocol addresses separated by points into integers? PHP has such a function ip2long. for example, echoi PHP: IP conversion integer)
This article is reproduced from :?? Http://blog.chinaunix.net/uid-10697776-id-2935481.html
?
?
?
How can we convert IP address protocol addresses separated by points into integers? PHP has such a function ip2long. for example:
echoip2long("10.2.1.3");
?>
We will get
167903491
How is this calculated? currently, I know there are two algorithms. First
Functionip2int ($ ip ){
// Divide the ip address into four segments: $ ip1, $ ip2, $ ip3, and $ ip4.
List ($ ip1, $ ip2, $ ip3, $ ip4) = explode (".", $ ip );
// Then multiply the first section by the third power of 256, the second section by the square of 256, and the third section by 256
// This is the value we get.
Return $ ip1 * pow (256) + $ ip2 * pow () + $ ip3 * + $ ip4;
}
?>
Second, bitwise operations
functionip2int($ip){
list($ip1,$ip2,$ip3,$ip4)=explode(".",$ip);
return($ip1<<24)|($ip2<<16)|($ip3<<8)|($ip4);
}
?>
We will find that some ip addresses are negative after being converted to integers, because the result is a signed integer with a maximum value of 2147483647. to convert it to unsigned, you can use
Sprintf ("% u", ip2long ($ ip );
It can be converted to a positive integer. In addition, long2ip can be converted back to the original IP address. You can also use ip2long to verify whether an ip address is valid, for example
Functionchk_ip ($ ip ){
If (ip2long ($ ip) = "-1 "){
Returnfalse;
}
Returntrue;
}
// Application
Var_export (chk_ip ("10.111.149.42 "));
Var_export (chk_ip ("10.111.256.42 "));
?>
True and false
?
?
?
?
?