Home  >  Article  >  Backend Development  >  Two practical methods to convert IP address to decimal number in PHP_PHP Tutorial

Two practical methods to convert IP address to decimal number in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 14:59:10840browse

How to convert ip address to decimal number in PHP? Nowadays, IP addresses are often used in PHP, but the IP addresses are not obtained in decimal. So how to convert the IP address into a decimal number in PHP is a headache for us. The following two methods are relatively simple methods that I have compiled to convert the IP address into a decimal number. Hope it helps everyone.
Method 1:

Copy code The code is as follows:

public function ipToLong(){
$ip = $_SERVER['REMOTE_ADDR'];
$ip = explode('.', $ip);
$ip = array_reverse($ip);//Array reverse
$r = 0;
for($i=0,$j=count($ip); $i<$j; $i++){
$r += $ip[$i] * pow( 256, $i);
}
$r = sprintf("%u", $r);
echo $r;
}

Method 2:
Copy code The code is as follows:

public function ipToLong(){
$ip = $_SERVER['REMOTE_ADDR'];
$ip = explode('.',$ip);
$r = ($ip[0] << 24) | ($ip[1] < ;< 16) | ($ip[2] << 8) | $ip[3];
if($r < 0) $r += 4294967296;
echo $r ;
}

The results of both results in the local server are 3232235877, and the IP used is 192.168.1.101. We use ping 192.168.1.101 and ping 3232235877 to check whether they are the same.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328175.htmlTechArticleHow to convert ip address to decimal number in PHP? Nowadays, IP addresses are often used in PHP, but the IP addresses are not obtained in decimal. So how to change the ip address in PHP...
Statement:
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