PHP equivalent for INET_NTOA and INET_ATON

Are there any PHP equivalents for these two functions? I tried to search, but did not see anything.

Thanks.

+3
source share
2 answers

You want ip2long()and long2ip().

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

As noted in the manual:

Note: since the PHP integer type and many IP addresses will be the result of negative integers, you need to use the format “% u” sprintf () or printf () to get a string representing the unsigned IP address.

+10
source

Here are the alternative PHP functions (plain 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))); 
}
+1
source

Source: https://habr.com/ru/post/1716756/


All Articles