3

Are there any PHP equivalents for these two functions? I tried searching but couldn't see anything.

Thanks.

2 Answers2

10

You want ip2long() and long2ip().

$ip = '192.0.34.166';
printf("%u\n", ip2long($ip)); // 3221234342

As it notes in the manual:

Note: Because PHP's integer type is signed, and many IP addresses will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

Greg
  • 316,276
  • 54
  • 369
  • 333
2

Here PHP alternative functions (simple copy/paste in your program) -

function inet_aton($ip)
{
    $ip = trim($ip);
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) return 0;
    return sprintf("%u", ip2long($ip));  
}


function inet_ntoa($num)
{
    $num = trim($num);
    if ($num == "0") return "0.0.0.0";
    return long2ip(-(4294967295 - ($num - 1))); 
}
user2253362
  • 81
  • 1
  • 3