PHP中将ip地址转成十进制数的两种实用方法

As we all know that long2ip works as ip1.ip2.ip3.ip4 (123.131.231.212)

long ip => (ip1 * 256 * 256 * 256) + (ip2 * 256 * 256) + (ip3 * 256) + ip4
2072242132 => (123 * 256 * 256 * 256) + (131 * 256 * 256) + (231 * 256) + 212
But what would be pseudo code for converting this number back into an IP address?

Also what would be the most suitable way to store IP addresses in MySQL for a traffic analytics website which will have about over 500 
IP lookups per second? Would it be better if a table with unique IDs is created for every single IP and then that is used for lookups? Thanks
$long = ip2long("123.131.231.212");

$ip = array();
array_unshift($ip, $long & 0xFF);
array_unshift($ip, ($long >>= 8) & 0xFF);
array_unshift($ip, ($long >>= 8) & 0xFF);
array_unshift($ip, ($long >>= 8) & 0xFF);

// $ip =
// Array
// (
//     [0] => 123
//     [1] => 131
//     [2] => 231
//     [3] => 212
// )

现在PHP中有很多时候都会用到ip地址,但是这个ip地址获取的时候都不是10进制的。那么PHP中如何将ip地址转成十进制数,下面为大家介绍下两种方法可以轻松实现

PHP中如何将ip地址转成十进制数呢?现在PHP中有很多时候都会用到ip地址,但是这个ip地址获取的时候都不是10进制的。那么PHP中如何将ip地址转成十进制数就是我们比较头疼的事情了,下面两种方法是我整理处理来相对比较简单的IP地址转成十进制数的方法。希望能对大家有所帮助。

方法一、

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

方法二、

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 ; 
} 

两个结果在本地服务器中的结果都是3232235877,运用的ip是192.168.1.101。我们用ping 192.168.1.101 和 ping 3232235877来进行检测,看是否一样。

原文地址:https://www.cnblogs.com/XACOOL/p/5614283.html