Immutable IP Address Library For PHP
Published on by Paul Redmond
The darsyn/ip package by Zan Baldwin is an Immutable value object for IPv4 and IPv6 addresses. The library includes several helper methods for IP ranges, broadcast and network addresses, subnet masks, and whether an IP is a certain type.
Here's brief example that shows off some of the functionality of this package:
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']);}
Here are some more examples of what you can do:
use Darsyn\IP\Version\Multi as IP; $ip = IP::factory('127.0.0.1'); // string("::ffff:7f00:1")echo $ip->getCompactedAddress(); // string("0000:0000:0000:0000:0000:ffff:7f00:0001")$ip->getExpandedAddress(); $ip = IP::factory('::ffff:7f00:1');// string("127.0.0.1")$ip->getProtocolAppropriateAddress(); $ip = IP::factory('127.0.0.1');// Returns the 16 byte (4 bytes for IPv4) binary string$binary = $ip->getBinary();
I'd recommend reading the documenation to get familiar with this package and its features. You can learn more about this package, get full installation instructions, and view the source code on GitHub.