Giter Site home page Giter Site logo

darsyn / ip Goto Github PK

View Code? Open in Web Editor NEW
245.0 10.0 20.0 1.29 MB

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

Home Page: http://darsyn.github.io/ip/

License: MIT License

PHP 100.00%
ipv4 ipv6 value-object immutable ip-address rfc doctrine php library packagist

ip's People

Contributors

coudenysj avatar michnovka avatar minterior avatar stopfstedt avatar zanbaldwin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ip's Issues

isVersion4 on getNetworkIp

When I do "getNetworkIp(23)->isVersion4()", it always returns false, nevertheless I gave an IPv4 address.

Update Documentation

Update the documentation for:

  • isMapped()
  • isDerived()
  • isCompatible()
  • isEmbedded()
  • IP::CIDR4TO6

getShortAddress missing in V4

I am upgrading my this package to version 4, but in version 3 their was a method "getShortAddress()" to get to short notation of an IPv4 AND IPv6 address.

In version 4 their are 2 different methods, getDotAddress (for version 4) and getCompactAddress (for version 6). But I don't wan't to check my version every time.

Is their a possibility to add this feature again?

[!] Doctrine 3 incompatibility

Hi guys! Is this package abandoned? Because I have a problem with it when Doctrine ORM is upgraded to 3.0 and DBAL to 4.0.

Starting from this:

Fatal error: Declaration of Darsyn\IP\Doctrine\AbstractType::convertToDatabaseValue($value, Doctrine\DBAL\Platforms\AbstractPlatform $platform) must be compatible with Doctrine\DBAL\Types\Type::convertToDatabaseValue(mixed $value, Doctrine\DBAL\Platforms\AbstractPlatform $platform): mixed in /var/app/vendor/darsyn/ip/src/Doctrine/AbstractType.php on line 85

And it's real:

public function convertToDatabaseValue($value, AbstractPlatform $platform)

vs

public function convertToPHPValue(mixed $value, AbstractPlatform $platform): mixed

It must be fixed. I can prepare the pull request, if you need it.

__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

Inconsistent Protocol Notation

The native inet_ntop function returns inconsistent IPv6 addresses, for example the IPv6 address ::ffff:c22:384e converted from binary to protocol notation actually results in ::ffff:12.34.56.78.

Implement custom formatter to return consistent IPv6 addresses.

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

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)

Incorrect behaviour with IPv4-mapped IPv6 addresses

::ffff:c000:280 (::ffff:192.0.2.128) represents the IPv4 address 192.0.2.128. A deprecated format for IPv4-compatible IPv6 addresses is ::c000:280 (::192.0.2.128). This library only supports the latter format.

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.

Add Code of Conduct

A CoC is unlikely to ever be needed for this project, but all projects should have one and I intent to lead by example - potential contributors should feel welcome and I hope a CoC helps with that.

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.

Add constant or helper method for IPv4 CIDR

Add either a constant or a helper method for converting IPv4 CIDR to IPv6 CIDR which this library uses for improved semantics. Eg:

<?php
use Darsyn\IP\IP;
$ip = new IP('127.0.0.1');

// Instead of:
$ip->getNetworkIp(96 + 12)

// Either (but a better constant name):
$ip->getNetworkIp(IP::CIDR4TO6 + 12)

// Or:
$ip->getNetworkIp(IP::cidr4to6(12))

If anyone reads this, what are you opinions over each method?

Versions

Nice little library. Could you possibly create a stable version branch rather than just "master".

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!

Better Handle IPv4 addresses in IPv6 notation.

  • Better handle IPv4-mapped IPv6 addresses (::ffff:7f00:1) by returning IPv4 notation from getShortAddress()
  • Start handling 6to4-derived addressing (2002:7f00:1::) in the version methods, also returning IPv4 notation from getShortAddress().
  • Internally store IPv4 addresses in IPv4-mapped format.

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.

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"

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?

Support native database types

Hi!
Do you plan to add support for native database types like INET in postgres? Here is library that already do this, but there are lack of value objects

Create Doctrine Type

Create a Doctrine DBAL type to store the ip type as a 16-byte binary sequence to automatically get reconstructed as a Darsyn\IP\IP object.

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.