IPv4 Converter

The League\Uri\IPv4\Converter is a IPv4 Host Converter.


use League\Uri\IPv4\Converter;
use League\Uri\IPv4\NativeCalculator;

$host = '0300.0250.0000.0001';
$converter = new Converter(new NativeCalculator());
$convertedHost = $converter->toDecimal($host);

echo $convertedHost; // returns ''


The Converter::toDecimal method tries to convert a host into a valid IPv4 decimal dot-notation representation based on the algorithm used by the WHATWG rules. The method only parameter should represent a host value.

To work as intended the class requires a League\Uri\IPv4\Calculator implementing class responsible for making all the calculations needed to perform the conversion between IPv4 representations.

The package comes bundled with three implementations:

For ease of usage the class exposes a fromEnvironment named constructor which will pick the correct implementation based on the available extensions.

If no calculator is provided a League\Uri\Exceptions\MissingFeature exception will be thrown. likewise, if no convertion is possible null is returned.


use League\Uri\IPV4\Converter;

$converter = Converter::fromEnvironment();
$converter->toDecimal('0');       // returns
$converter->toDecimal('toto.be'); // returns null

The same functionality is provided to convert the IPv4 to Octal and Hexadecimal representation.


use League\Uri\IPV4\Converter;

$converter = Converter::fromEnvironment();
$converter->toDecimal('0xc0a821');         // returns ""
$converter->toOctal('0xc0a821');           // returns "0300.0250.0002.0001"
$converter->toHexadecimal(''); // returns "0xc0a821"

since version 7.2.0

It is possible to determine if a given domain is or can be converted to an IPv4 host the new Converter::isIpv4 method. The method will return true if the submitted domain is an IPv4 host or is convertible to an IPv4 host.


use League\Uri\Ipv4\Converter;

$converter = Converter::fromEnvironment();
$converter->isIpv4('0xc0a821');     // return true
$converter->isIpv4(''); // return true
$converter->isIpv4('bébé.be');      // return false