php-ip icon indicating copy to clipboard operation
php-ip copied to clipboard

IPBlock::create() does not work with humanReadable(false) IP strings

Open bkuebler opened this issue 4 years ago • 1 comments

For me it's unsure if this is a wanted behaviour but, if i try to create an IPBlock from a non human readable ip prefix it will fail.

Code to reproduce

$block = IPBlock::create('192.168.1.0/24');
$nonHumanString = $block->getFirstIp()->humanReadable(false) . '/' . $block->getPrefixLength();
$failedBlock = IPBlock::create($nonHumanString);

bkuebler avatar Jul 22 '21 09:07 bkuebler

Good find. I wouldn't say it's a wanted behaviour, but it looks like rather like an unwanted side effect of trying to be consistent between IPv4 and IPv6.

First of all, the argument for humanReadable() doesn't mean "not human readable". It's whether or not you want the "short form" of the IP. This has been added for IPv6, which, by nature, can be shortened. For example you write 2a01:8200:: instead of 2a01:8200:0000:0000:0000:0000:0000:0000.

With IPv6 indeed it works fine:

$ip = new IPv6('2a01:8200::');
$longForm = $ip->humanReadable(false);
echo $longForm, " => ",new IPv6($longForm);
// outputs 2a01:8200:0000:0000:0000:0000:0000:0000 => 2a01:8200::

Now for IPv4, arguably there is no "long form", since there is no standard way to shorten the IP (as far as I know). This is only here because it exists in IPv6, but in reality I don't know a use case for writing 192.168.000.001. The question is whether such a representation is actually valid or not - this is unclear to me. The interesting part is that constructing an IP address relies on PHP's internal filter_var() method, and PHP thinks it's not valid:

filter_var('192.168.000.001', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
// returns false

I can see a few options:

  • Either it is a valid string representation, and then it's a bug with PHP's filter_var
  • Or it's not valid, and probably this feature should be either removed for IPv4, or at least clearly documented that this will produce an invalid IP address representation.

What is your use case for this?

rlanvin avatar Jul 22 '21 18:07 rlanvin