2 && \ctype_xdigit(\substr($last, 2)); } /** * Returns the four-byte binary form of a host that a transport reads as a * numeric IPv4 address, or null when it reads it as a name. * * The shape test is Handler\HostValidator::isNumericIpv4Host(); this * method adds the range checks that predicate omits: every part but the * last must fit one octet, and the last must fit the octets the earlier * parts left. A trailing root dot is not swallowed, unlike libcurl 8.21.0 * and later, because assertRequestHost() rejects that spelling first. */ public static function numericIpv4ToBinary(string $host): ?string { if (!Handler\HostValidator::isNumericIpv4Host($host)) { return null; } $values = []; foreach (\explode('.', $host) as $part) { $values[] = self::numericIpv4PartValue($part); } // Every accepted value is a whole number no larger than 0xFFFFFFFF, // which a float holds exactly, so the arithmetic below is correct on a // 32-bit build too, where the widest part overflows an integer. $address = (float) \array_pop($values); $packed = ''; foreach ($values as $value) { if ($value > 255.0) { return null; } $packed .= \chr((int) $value); } $width = 4 - \count($values); if ($address >= 256.0 ** $width) { return null; } for ($shift = $width - 1; $shift >= 0; --$shift) { $packed .= \chr((int) \fmod(\floor($address / 256.0 ** $shift), 256.0)); } return $packed; } /** * Returns the value of one accepted part as a float, so a part filling * all four octets such as 2130706433 stays exact on every integer width. */ private static function numericIpv4PartValue(string $part): float { if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) { return (float) \hexdec((string) \substr($part, 2)); } if ($part[0] === '0') { return (float) \octdec($part); } return (float) $part; } private function __construct() { // cannot be instantiated } }