I am in the process of optimizing a script that handles members IPs. This converts to 4-byte char and works fine -
function ip2bytes($ip)
{
$res = '';
$parts = explode('.', $ip);
if (count($parts) !== 4)
return null;
for ($i = 0; $i < 4; $i ) {
$b = $parts[$i];
if (!is_numeric($b))
return null;
$b = intval($b);
if ($b < 0 || $b >= 256)
return null;
$res .= chr($b);
}
return $res;
}
$bs = ip2bytes($user['ip']);
However, this one-liner provides the exact same result:
$bs = inet_pton($user['ip']);
var dumping both produce same expected result:
string(4) "�nd-"
string(4) "�nd-"
Other than checks, what is the difference? I want to know if I can rely on inet_pton() instead of the overhead of a function call when this PHP built-in function provides the same result, as this script gets a lot of GET requests concurrently. I want a lighter codebase.
Any advice is appreciated.
CodePudding user response:
In order to store ipv4 addresses effectively, 32-bit integer numbers are usually used.
$ip = "127.1.2.3";
$int32 = ip2long($ip); // int(2130772483)
inet_pton returns a 4-byte string for ipv4.
$bs = inet_pton($ip); //"\x7f\x01\x02\x03"
Your ip2bytes function returns the same result. A third variant makes it clear what is being done.
$bs = pack('N',ip2long($ip));
These functions are all so fast that the time of a few microseconds is mostly negligible compared to other actions. You don't have to worry about this problem when using inet_pton.