PHP - ip2long not converting properly

I'm currently trying to learn php and am having trouble with the ip2long() function.

$ipToConvert = '';
$ip = ip2long($ipToConvert);

echo $ipToConvert;
echo $ip;

The expected result is that the first echo displays and the second echo displays 46211334.

The result I am getting is that the first one does indeed display, the second echo however displays 773131554.

1 answer

  • answered 2018-11-08 08:17 Federico klez Culloca

    That's not how ip2long works. It converts the 4 bytes to a long value.

    So for example a.b.c.d gets converted to (a << 24) + (b << 16) + (c << 8) + d

    What you probably want is removing the dots from the string and converting the result to a number:

    intval(str_replace('.', '', $ip));

    Or, since the result could possibly overflow, convert to a float

    floatval(str_replace('.', '', $ip));