3v4l.org

run code in 300+ PHP versions simultaneously
<?php declare(strict_types=1); class StackOverflowCopyPaste { /** @var int $v4MaskBits */ private $v4MaskBits; /** @var int $v6MaskBits */ private $v6MaskBits; /** * @param int $v4MaskBits * @param int $v6MaskBits */ public function __construct(int $v4MaskBits = 24, int $v6MaskBits = 48) { $this->v4MaskBits = $v4MaskBits; $this->v6MaskBits = $v6MaskBits; } /** * Return the given subnet for an IP and the configured mask bits * * Determine if the IP is an IPv4 or IPv6 address, then pass to the correct * method for handling that specific type. * * @param string $ip * @return string */ public function getSubnet(string $ip): string { if (\preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $ip)) { return $this->getIPv4Subnet( $ip, (int) ($this->v4MaskBits ?? 32) ); } return $this->getIPv6Subnet( $ip, (int) ($this->v6MaskBits ?? 128) ); } /** * Return the given subnet for an IPv4 address and mask bits * * @param string $ip * @param int $maskBits * @return string */ public function getIPv4Subnet(string $ip, int $maskBits = 32): string { $binary = \inet_pton($ip); for ($i = 32; $i > $maskBits; $i -= 8) { $j = \intdiv($i, 8) - 1; $k = (int) \min(8, $i - $maskBits); $mask = (0xff - ((1 << $k) - 1)); $int = \unpack('C', $binary[$j]); $binary[$j] = \pack('C', $int[1] & $mask); } return \inet_ntop($binary).'/'.$maskBits; } /** * Return the given subnet for an IPv6 address and mask bits * * @param string $ip * @param int $maskBits * @return string */ public function getIPv6Subnet(string $ip, int $maskBits = 48): string { $binary = \inet_pton($ip); for ($i = 128; $i > $maskBits; $i -= 8) { $j = \intdiv($i, 8) - 1; $k = (int) \min(8, $i - $maskBits); $mask = (0xff - ((1 << $k) - 1)); $int = \unpack('C', $binary[$j]); $binary[$j] = \pack('C', $int[1] & $mask); } return \inet_ntop($binary).'/'.$maskBits; } } $mask = new StackOverflowCopyPaste(24, 48); var_dump($mask->getSubnet('12.34.56.78')); var_dump($mask->getSubnet('2001:0db8:85a3:0000:0000:8a2e:0370:7334'));
Output for 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.28, 8.4.1 - 8.4.14, 8.5.0 - 8.5.1
string(13) "12.34.56.0/24" string(18) "2001:db8:85a3::/48"
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.
Output for 5.6.0 - 5.6.40
Warning: Unsupported declare 'strict_types' in /in/i2ufm on line 2 Fatal error: Default value for parameters with a class type hint can only be NULL in /in/i2ufm on line 15
Process exited with code 255.

preferences:
215.84 ms | 408 KiB | 5 Q