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 →
Image Dominant Color and HEIC Support in Laravel 13.24 image

Image Dominant Color and HEIC Support in Laravel 13.24

Read article
Official Laravel Zed Extension: LSP for PHP & Blade image

Official Laravel Zed Extension: LSP for PHP & Blade

Read article
Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD image

Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD

Read article
PhpStorm 2026.2 Released image

PhpStorm 2026.2 Released

Read article
Laravel Doctor: Diagnose Your App With One Artisan Command image

Laravel Doctor: Diagnose Your App With One Artisan Command

Read article
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article