0

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.

WiiLF
  • 304
  • 3
  • 11
  • Note: For your ip2bytes function, it explodes on '.' and so can **ONLY** handle IPv4 data. For inet_pton() , it handles both IPv4 and IPv6 data – Ken Lee Feb 27 '22 at 00:55
  • Thank you so much! I was thinking about that as well according to the php.net docs on this internal function. Can you go as far as to recommend this one-liner in place of the custom function? – WiiLF Feb 27 '22 at 02:00
  • 1
    Unless this function gets called in a loop thousands of times, I doubt you’ll see any performance differences. Is it a 100% identical replacement? I can’t say for sure (except for the noted ipv6 stuff), but as long as you always use it and `inet_ntop` you should be safe. – Chris Haas Feb 27 '22 at 03:16

1 Answers1

1

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.

jspit
  • 7,276
  • 1
  • 9
  • 17