PHP: IP address transformation and shaping

Source: Internet
Author: User
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

?

?

?

?

?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.