/** * Try get the range instance starting from its string representation. * * @param string|mixed $range * * @return static|null */ public static function fromString($range) { $result = null; if (is_string($range) && strpos($range, '*') !== false) { if ($range === '*.*.*.*') { $result = new static(IPv4::fromString('0.0.0.0'), IPv4::fromString('255.255.255.255'), 4); } elseif (strpos($range, '.') !== false && preg_match('/^[^*]+((?:\\.\\*)+)$/', $range, $matches)) { $asterisksCount = strlen($matches[1]) >> 1; $fromAddress = IPv4::fromString(str_replace('*', '0', $range)); if ($fromAddress !== null) { $fixedBytes = array_slice($fromAddress->getBytes(), 0, -$asterisksCount); $otherBytes = array_fill(0, $asterisksCount, 255); $toAddress = IPv4::fromBytes(array_merge($fixedBytes, $otherBytes)); $result = new static($fromAddress, $toAddress, $asterisksCount); } } elseif ($range === '*:*:*:*:*:*:*:*') { $result = new static(IPv6::fromString('::'), IPv6::fromString('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 8); } elseif (strpos($range, ':') !== false && preg_match('/^[^*]+((?::\\*)+)$/', $range, $matches)) { $asterisksCount = strlen($matches[1]) >> 1; $fromAddress = IPv6::fromString(str_replace('*', '0', $range)); if ($fromAddress !== null) { $fixedWords = array_slice($fromAddress->getWords(), 0, -$asterisksCount); $otherWords = array_fill(0, $asterisksCount, 0xffff); $toAddress = IPv6::fromWords(array_merge($fixedWords, $otherWords)); $result = new static($fromAddress, $toAddress, $asterisksCount); } } } return $result; }
/** * Create an IPv4 representation of this address (if possible, otherwise returns null). * * @return IPv4|null */ public function toIPv4() { $result = null; if (strpos($this->longAddress, '2002:') === 0) { $result = IPv4::fromBytes(array_slice($this->getBytes(), 2, 4)); } return $result; }