Immutable IP Address Library For PHP

Packages

August 13th, 2021

ip-value-object-featured.png

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:

1use Darsyn\IP\Exception;
2use Darsyn\IP\Version\IPv4;
3 
4try {
5 $ip = IPv4::factory('192.168.0.1');
6} catch (Exception\InvalidIpAddressException $e) {
7 exit('The IP address supplied is invalid!');
8}
9 
10$companyNetwork = IPv4::factory('216.58.198.174');
11if (!$ip->inRange($companyNetwork, 25)) {
12 throw new \Exception('Request not from a known company IP address.');
13}
14 
15// Is it coming from the local network?
16if (!$ip->isPrivateUse()) {
17 record_visit($ip->getBinary(), $_SERVER['HTTP_USER_AGENT']);
18}

Here are some more examples of what you can do:

1use Darsyn\IP\Version\Multi as IP;
2 
3$ip = IP::factory('127.0.0.1');
4 
5// string("::ffff:7f00:1")
6echo $ip->getCompactedAddress();
7 
8// string("0000:0000:0000:0000:0000:ffff:7f00:0001")
9$ip->getExpandedAddress();
10 
11 
12$ip = IP::factory('::ffff:7f00:1');
13// string("127.0.0.1")
14$ip->getProtocolAppropriateAddress();
15 
16$ip = IP::factory('127.0.0.1');
17// Returns the 16 byte (4 bytes for IPv4) binary string
18$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.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.