(PHP 4, PHP 5, PHP 7, PHP 8)
long2ip — Converts a long integer address into a string in (IPv4) Internet standard dotted format
The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the long integer representation.
ip
A proper address representation in long integer.
Returns the Internet IP address as a string .
Version | Description |
---|---|
8.4.0 | Return type changed from string |false to string . |
7.1.0 |
The parameter type of ip has been
changed from string to int .
|
Note:
On 32-bit architectures, casting integer representations of IP addresses from string to int will not give correct results for numbers which exceed
PHP_INT_MAX
.
If the function doesn't exist:
<?
if (!function_exists("long2ip")) {
function long2ip($long) {
// Valid range: 0.0.0.0 -> 255.255.255.255
if ($long < 0 || $long > 4294967295) return false;
$ip = "";
for ($i=3;$i>=0;$i--) {
$ip .= (int)($long / pow(256,$i));
$long -= (int)($long / pow(256,$i))*pow(256,$i);
if ($i>0) $ip .= ".";
}
return $ip;
}
}
?>
For a 32bit safe long2ip, which can accept string or signed integer input, try:
function safelong2ip($long) {
$binStr = sprintf("%032s", decbin((float)$long));
if (strlen($binStr) != 32) {
throw new Exception("Invalid IPv4 subnet!");
}
$ipArr = [];
for ($i = 0; $i < 4; ++$i) {
$ipArr[] = bindec(substr($binStr, $i*8, 8));
}
return implode('.', $ipArr);
}