Immutable value object for IPv4 and IPv6 addresses, including helper methods and Doctrine support.

Overview

Build Status

IP is an immutable value object for (both version 4 and 6) IP addresses. Several helper methods are provided for ranges, broadcast and network addresses, subnet masks, whether an IP is a certain type (defined by RFC's), etc.

This project aims for simplicity of use and any contribution towards that goal - whether a bug report, modifications to the codebase, or an improvement to the accuracy or readability of the documentation - are always welcome.

Documentation

Full documentation is available in the docs/ folder.

Code of Conduct

This project includes and adheres to the Contributor Covenant as a Code of Conduct.

Upgrading

This library is fairly similar to how it was in 3.3.1; the main differences are:

Brief Example

<?php

use Darsyn\IP\Exception;
use Darsyn\IP\Version\IPv4;

try {
    $ip = IPv4::factory('192.168.0.1');
} catch (Exception\InvalidIpAddressException $e) {
    exit('The IP address supplied is invalid!');
}

$companyNetwork = IPv4::factory('216.58.198.174');
if (!$ip->inRange($companyNetwork, 25)) {
    throw new \Exception('Request not from a known company IP address.');
}

// Is it coming from the local network?
if (!$ip->isPrivateUse()) {
    record_visit($ip->getBinary(), $_SERVER['HTTP_USER_AGENT']);
}

License

Please see the separate license file included in this repository for a full copy of the MIT license, which this project is licensed under.

Authors

If you make a contribution (submit a pull request), don't forget to add your name here!

Comments
  • Automatically use the CIDR4TO6 constant for IPv4 addresses.

    Automatically use the CIDR4TO6 constant for IPv4 addresses.

    I was wondering if it would be feasible to automatically use the CIDR4TO6 if the current object holds a IPv4 address.

    In the following snippet, the IP::CIDR4TO6 + could added in the getNetworkIP method (as we now the IP it holds is v4):

    $ip = new IP('12.34.56.78');
    // Get the network address of an IP address given a subnet mask.
    $networkIp = $ip->getNetworkIP(IP::CIDR4TO6 + 19);
    $networkIp->getShortAddress(); // string() "12.34.32.0"
    
    opened by coudenysj 5
  • Your data could not be encoded because it contains invalid UTF8 characters.

    Your data could not be encoded because it contains invalid UTF8 characters.

    Since I have implemented Darsyn, I can't output my object that contains the IP Address in json.

    This is a dump of the result that should me encoded to json: array:128 [▼ 0 => IpAddress {#9856 ▼ -id: null -ipAddress: IP {#9857 ▼ -ip: b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00À¨\x01\x00" -version: null } -hostname: null -hostDescription: null -phone: null -mac: null -additionalInformation: null -createdAt: null -updateAt: null -subnet: Subnet {#8158 ▶} -provider: null -user: null -datacenter: null }

    But when I try to encoded it to json, I receive the error: Your data could not be encoded because it contains invalid UTF8 characters.

    bug 
    opened by TheJenne18 5
  • Some valid IPs are detected as invalid

    Some valid IPs are detected as invalid

    Despite filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) and inet_pton($ip) are not failing (thus, the IP is valid), after executing the code:

                $ip = current(unpack('a4', inet_pton($ip)));
                $ip = str_pad($ip, 16, "\0", STR_PAD_LEFT);
    

    is failing with some IPs because the final str_len of $ip is 15 instead of 16.

    Example IP: 37.152.208.254

    opened by minterior 4
  • PostgreSQL 9.5 saves nothing

    PostgreSQL 9.5 saves nothing

    Hi! Thanx for your extension, but there something wrong with doctrine support. IP column is empty in the table after flush. php-fpm7.0 postresql 9.5 Doctrine 2.5.5-DEV

    Thank You!

    opened by gigi 3
  • __toString

    __toString

    Hello,

    Nice work.

    Is it possible to add à __toString method in Multi entity ? The __toString method should return $this->getProtocolAppropriateAddress(). Twig rendering and forms will be simpler with a __toString()

    Regards

    opened by FredDut 2
  • Expanded IPv6 Formatter

    Expanded IPv6 Formatter

    This PR adds a new Formatter that outputs IPv6 addresses in their expanded form.

    I didn't squash the commits intentionally so you can see the implementation where ConsistentFormatter::ntopVersion6() remains a private function.

    opened by gjuric 2
  • Default gateway

    Default gateway

    Hello,

    Is it possible to add the feature to receive a default gateway from a subnet?

    Same as we can to with getNetworkIp and getBroadcastIp.

    Basically it is the network address + 1.

    enhancement 
    opened by TheJenne18 2
  • Warning: strlen() expects parameter 1 to be string, resource given

    Warning: strlen() expects parameter 1 to be string, resource given

    Getting an error Warning: strlen() expects parameter 1 to be string, resource given while trying to get an object with the type ip

    config

    php-fpm 7.0
    postresql 9.6.3
    darsyn/ip                                3.3.0 
    doctrine/annotations                     v1.4.0  
    doctrine/cache                           v1.6.1 
    doctrine/collections                     v1.4.0
    doctrine/common                          v2.7.2 
    doctrine/dbal                            v2.5.12
    doctrine/doctrine-bundle                 1.6.8
    doctrine/doctrine-cache-bundle           1.3.0
    doctrine/inflector                       v1.1.0  
    doctrine/instantiator                    1.0.5  
    doctrine/lexer                           v1.0.1
    doctrine/orm                             v2.5.6
    

    Stack Trace

    [1] Symfony\Component\Debug\Exception\ContextErrorException: Warning: strlen() expects parameter 1 to be string, resource given
    at n/a
        in vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/ConversionException.php line 44
    
    at Symfony\Component\Debug\ErrorHandler->handleError('2', 'strlen() expects parameter 1 to be string, resource given', 'vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/ConversionException.php', '44', array('value' => resource, 'toType' => 'ip'))
        in  line 
    
    at strlen(resource)
        in vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/ConversionException.php line 44
    
    at Doctrine\DBAL\Types\ConversionException::conversionFailed(resource, 'ip')
        in vendor/darsyn/ip/src/Doctrine/IpType.php line 58
    
    at Darsyn\IP\Doctrine\IpType->convertToPHPValue(resource, object(PostgreSQL92Platform))
        in vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php line 131
    
    at Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator->hydrateRowData(array('id_1' => '1', 'date_2' => '2017-07-10 10:54:32', 'ip_3' => resource, 'value_4' => '6'), array())
        in vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php line 69
    
    at Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator->hydrateAllData()
        in vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php line 147
    
    at Doctrine\ORM\Internal\Hydration\AbstractHydrator->hydrateAll(object(PDOStatement), object(ResultSetMapping), array())
        in vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php line 720
    
    at Doctrine\ORM\Persisters\Entity\BasicEntityPersister->load(array('id' => '1'), null)
        in vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php line 730
    
    at Doctrine\ORM\Persisters\Entity\BasicEntityPersister->loadById(array('id' => '1'))
        in vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php line 462
    
    at Doctrine\ORM\EntityManager->find('AppBundle\Entity\MyEntity', array(), null, null)
        in vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php line 154
    
    at Doctrine\ORM\EntityRepository->find('1')
        in src/AppBundle/Controller/TestController.php line 21
    
    at AppBundle\Controller\TestController->testAction(object(Request))
        in  line 
    
    at call_user_func_array(array(object(TestController), 'testAction'), array(object(Request)))
        in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php line 144
    
    at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
        in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php line 64
    
    at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
        in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/DependencyInjection/ContainerAwareHttpKernel.php line 69
    
    at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request), '1', true)
        in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php line 185
    
    at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
        in web/app_dev.php line 33
    
    opened by jenyak 2
  • Symfony throws warnings due to missing return type

    Symfony throws warnings due to missing return type

    I have Symfony 5.4.6 with PHP 8.1 and I get these errors in Console when doing doctrine:migrations:diff

    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::getSQLDeclaration()" might add "string" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::convertToPHPValue()" might add "mixed" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::convertToDatabaseValue()" might add "mixed" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::getName()" might add "string" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::getBindingType()" might add "int" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::requiresSQLCommentHint()" might add "bool" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    
    opened by michnovka 1
  • Add @return PHPDoc annotations to AbstractType.php

    Add @return PHPDoc annotations to AbstractType.php

    Get rid of error messages like:

    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::getSQLDeclaration()" might add "string" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::convertToPHPValue()" might add "mixed" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::convertToDatabaseValue()" might add "mixed" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::getName()" might add "string" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::getBindingType()" might add "int" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    2022-03-06T21:58:26+01:00 [info] User Deprecated: Method "Doctrine\DBAL\Types\Type::requiresSQLCommentHint()" might add "bool" as a native return type declaration in the future. Do the same in child class "Darsyn\IP\Doctrine\AbstractType" now to avoid errors or add an explicit @return annotation to suppress this message.
    
    

    I used PHPDoc annotations and not explicit return types to keep compatibility with PHP5.6+ as your composer conf file says. Please merge, I get these errors all the time in my console. Thanks

    opened by michnovka 1
  • Behaviour of Type Methods in Multi

    Behaviour of Type Methods in Multi

    If Multi is holding an IPv4-embedded address, should that IP be treated purely as IPv4 or should it treated as potentially both IPv4 and IPv6?

    Example

    The address 0.0.0.1 (when using the compatible embedding strategy) is a loopback address if viewing as IPv6 (::1), but also not a loopback address (127.x.x.x) if viewing as an IPv4-embedded address.

    Implementation

    The type methods can be implemented as either of the following two examples, depending on what is decided:

    // Checks if it a loopback address according to IPv6, if not try rechecking
    // as IPv4 (if it's embedded). This is the current (4.0.1) behaviour.
    return parent::isLoopback()
        || $this->isEmbedded()
        && (new IPv4($this->getShortBinary()))->isLoopback();
    
    // Try as both IPv4->isLoopback() and IPv6->isLoopback().
    Multi::factory('0.0.0.1', new Strategy\Compatible)->isLoopback(); // bool(true)
    
    // If it's an IPv4-embedded address, check as IPv4 only.
    // If it's not, check as IPv6.
    return $this->isEmbedded()
        ? (new IPv4($this->getShortBinary()))->isLoopback()
        : parent::isLoopback();
    
    // Try only as both IPv4->isLoopback() because it's an IPv4-embedded address.
    Multi::factory('0.0.0.1', new Strategy\Compatible)->isLoopback(); // bool(false)
    
    question breaking change 
    opened by zanbaldwin 1
  • Problem with QueryBuilder

    Problem with QueryBuilder

    Hello, I'm facing a problem with querybuilder (Symfony 5.4): I've created a basic entity:

    /**
     * @ORM\Entity(repositoryClass=JustipRepository::class)
     */
    class Justip
    {
        /**
         * @ORM\Id
         * @ORM\GeneratedValue
         * @ORM\Column(type="integer")
         */
        private $id;
    
        /**
         * @ORM\Column(type="ip", nullable=true)
         */
        private $ip;
    
        public function getId(): ?int
        {
            return $this->id;
        }
    
        public function getIp()
        {
            return $this->ip;
        }
    
        public function setIp($ip): self
        {
            $this->ip = $ip;
    
            return $this;
        }
    }
    

    in my controller

    $ip = Multi::factory('192.168.0.1');
    

    if use the magic method , it 's ok $entities = $this->em->getRepository(Justip::class)->findByIp($ip->getBinary());

    if use the querybuilder it's not ok

      public function findByExampleField($value): array
       {
           return $this->createQueryBuilder('j')
               ->andWhere('j.ip = :val')
               ->setParameter('val', $value)
               ->getQuery()
               ->getResult()
           ;
       }
    

    $entities = $this->em->getRepository(Justip::class)->findByExampleField($ip->getBinary());

    With findByIp , the runable query is SELECT j0_.id AS id_0, j0_.ip AS ip_1 FROM justip j0_ WHERE j0_.ip = \0x00000000000000000000FFFFC0A80001;

    With querybuilder the runable query is SELECT j0_.id AS id_0, j0_.ip AS ip_1 FROM justip j0_ WHERE j0_.ip = 0x00000000000000000000FFFFC0A80001;

    I don't know how to tell doctrine that the binary value is binary. Is there something wrong in my code?

    opened by FredDut 1
Releases(4.1.0)
  • 4.1.0(May 19, 2022)

    • Added IpInterface::equals() method for comparing two IP addresses.
    • Added getCommonCidr(IpInterface $ip): int for determining how in range two IP addresses are according to their common CIDR value.
    • Added isBenchmarking(), isDocumentation(), and isPublicUse() type methods for both IPv4 and IPv6 addresses.
    • Added isBroadcast(), isShared(), and isFutureReserved() type methods for IPv4 addresses.
    • Added getMulticastScope(), isUniqueLocal(), isUnicast(), and isUnicastGlobal() type methods for IPv6 addresses.
    • Added Ipv6::fromEmbedded() factory method to create an instance of an IPv4-embedded address as IPv6 instead of Multi.
    • Made internal helper methods for dealing with binary data into utility classes: Darsyn\IP\Util\Binary and Darsyn\IP\Util\MbString.
    • Complete documentation overhaul
    • Increase test coverage.
    • Started using static analysis both locally and via GitHub actions.
    • Documentation and tests are excluded from the Git archive to reduce download size when installing Composer dependency as dist.
    • Updated Code of Conduct to Contributor Covenant v2.1
    Source code(tar.gz)
    Source code(zip)
PHP library to handle IPv4, IPv6 and IP ranges

IPLib - Handle IPv4, IPv6 and IP ranges Introduction IPLib is a modern, PSR-compliant, test-driven IP addresses and subnets manipulation library. It i

Michele Locati 212 Jan 3, 2023
Easy management of Virtualization technologies including KVM, Xen, OpenVZ, Virtuozzo, and LXC/LXD including unified commands, monitoring, template management, and many more features.

ProVirted About Easy management of Virtualization technologies including KVM, Xen, OpenVZ, Virtuozzo, and LXC/LXD including unified commands, monitori

null 2 Aug 22, 2022
Share value objects that contain the same primitive value as a singleton

sharable-value-objects Share value objects that contain the same primitive value as a singleton. Singletons are kept under WeakReference objects. Inst

mpyw 5 Nov 14, 2021
Allows generate class files parse from json and map json to php object, including multi-level and complex objects;

nixihz/php-object Allows generate class files parse from json and map json to php object, including multi-level and complex objects; Installation You

zhixin 2 Sep 9, 2022
Allows reflection of object attributes, including inherited and non-public ones

sebastian/object-reflector Allows reflection of object attributes, including inherited and non-public ones. Installation You can add this library as a

Sebastian Bergmann 6k Jan 4, 2023
A PHP 7 value objects helper library.

valueobjects Requirements Requires PHP >= 7.1 Installation Through Composer, obviously: composer require funeralzone/valueobjects Extensions This lib

Funeral Zone 56 Dec 16, 2022
PHP library that helps to map any input into a strongly-typed value object structure.

Valinor • PHP object mapper with strong type support Valinor is a PHP library that helps to map any input into a strongly-typed value object structure

Team CuyZ 873 Jan 7, 2023
Decimal handling as value object instead of plain strings.

Decimal Object Decimal value object for PHP. Background When working with monetary values, normal data types like int or float are not suitable for ex

Spryker 16 Oct 24, 2022
Yet another Value Object Library (YAVOL)

Yet Another DDD Library Value object This library is a foundation in order to implement the Value Object pattern. It helps you to introduce some DDD s

YADDDL 3 Nov 17, 2022
Provides JSON pointer as a value object

json-pointer Provides JSON pointer as a value object. Installation Run composer require ergebnis/json-pointer Usage ReferenceToken You can create a Re

null 3 Dec 15, 2022
An opinionated extension package for Laravel Orchid to extend its table handling capabilities, and some further useful helper methods.

OrchidTables An opinionated extension package for Laravel Orchid to extend its table handling capabilities, and some further useful helper methods. In

null 25 Dec 22, 2022
Source control integration plugin framework for MantisBT, including support for Github, Gitlab, Bitbucket, Gitweb, Cgit, Subversion, Mercurial and more

Source control integration plugin framework for MantisBT, including support for Github, Gitlab, Bitbucket, Gitweb, Cgit, Subversion, Mercurial and more

MantisBT Community Plugins 175 Sep 3, 2022
A library for IP addresses calculations

PHP IP tools This library provides tooling for IP address calculations based on rlanvin/php-ip Free IP blocks calculation Compute the best possible al

HiQDev 4 Mar 25, 2022
Laravel Pipeline with DB transaction support, events and additional methods

Laravel Enhanced Pipeline Laravel Pipeline with DB transaction support, events and additional methods #StandWithUkraine Installation Install the packa

Michael Rubél 33 Dec 3, 2022
Support for PHP 8.1 enums in Doctrine.

Doctrine Native Enums This library provides first-class support to PHP Enums, introduced in PHP 8.1, within your Doctrine entities. Installation compo

Beno!t POLASZEK 14 Dec 15, 2022
Your alter ego object. Takes the best of object and array worlds.

Supporting Opensource formapro\values is an MIT-licensed open source project with its ongoing development made possible entirely by the support of com

FormaPro 31 Jun 25, 2021
An article about alternative solution for convert object into a JSON Object for your api.

Do we really need a serializer for our JSON API? The last years I did build a lot of JSON APIs but personally was never happy about the magic of using

Alexander Schranz 1 Feb 1, 2022
This is an experiment to export all RFCs from the PHP wiki into Git, including the change history for each RFC (along with the date and author of each change). This is not meant to replace the wiki.

PHP Requests for Comments (RFCs) About This repository is an experiment to export all RFCs from the PHP wiki into Git, including the change history fo

Ben Ramsey 34 Jun 20, 2022
This Pocketmine-MP plugin is a plugin including a complete faction system.

SimpleFaction Simple faction plugin replacing FactionsPro which is no longer updated. Commands Command Name Command Description Available for /f help

Ayzrix 33 Dec 19, 2022