Home >Backend Development >PHP Tutorial >How to convert ip address to decimal number in PHP_PHP Tutorial

How to convert ip address to decimal number in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 14:53:16996browse

How to convert ip address to decimal number in PHP? Nowadays, ip address is used many times in PHP, but the ip address is 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:

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:

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.

Some friends may not know that both mysql and php provide IP conversion decimal number function

 MySQL provides two functions, INET_ATON and INET_NTOA, to convert between addresses and integers.

1. IP is converted from dotted format to digital format.

The code is as follows

mysql> select inet_aton('127.0.0.1');

 +---------------------+

| inet_aton('127.0.0.1') |

 +---------------------+

 | 2130706433 |

 +---------------------+

 1 row in set (0.00 sec)

 2. Convert IP from digital format to dotted format.

The code is as follows

mysql> select inet_ntoa(2130706433);

+-----------------------+

| inet_ntoa(2130706433) |

+-----------------------+

 | 127.0.0.1 |

+-----------------------+

 1 row in set (0.00 sec)

PHP can directly use the ip2long function

The code is as follows

echo ip2long('192.168.1.38');

Output: 3232235814

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371387.htmlTechArticleHow to convert ip address to decimal number in PHP? IP address is used many times in PHP now. But this IP address is not in decimal when obtained. 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