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'));

preferences:
17.21 ms | 402 KiB | 5 Q