Laravel Packages

Immutable IP Address Library For PHP

Published
Immutable IP Address Library For PHP image

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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article