Last active
February 4, 2025 19:32
-
-
Save kimboslice99/96ee6f0a069f3706aa34f033f7e97027 to your computer and use it in GitHub Desktop.
Simple class for easy IP operations in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class IPUtilities { | |
static function IsInIPv4Range($ipaddress, $range){ | |
// convert the ip to long respresentation | |
$long = ip2long($ipaddress); | |
// split the range/cidr | |
$parts = explode('/', $range); | |
// convert the range to long representation | |
$rangeAddr = ip2long($parts[0]); | |
// binary mask | |
$cidrMask = -1 << (32 - (int)$parts[1]); | |
return ($long & $cidrMask) == ($rangeAddr & $cidrMask); | |
} | |
static function IsIpv6InSubnet($ip, $subnet, $prefix) { | |
// Convert IPv6 addresses to binary strings | |
$ipBinary = inet_pton($ip); | |
$subnetBinary = inet_pton($subnet); | |
if ($ipBinary === false || $subnetBinary === false || $prefix < 0 || $prefix > 128) { | |
return false; // Invalid input | |
} | |
// Generate an IPv6 mask as a binary string | |
$mask = self::GenerateIpv6Mask($prefix); | |
// Apply the mask and compare | |
return ($ipBinary & $mask) === ($subnetBinary & $mask); | |
} | |
private static function GenerateIpv6Mask($prefix) { | |
$mask = str_repeat("\xFF", (int)($prefix / 8)); // Full bytes | |
if ($prefix % 8 !== 0) { | |
$mask .= chr(0xFF << (8 - ($prefix % 8))); // Partial byte | |
} | |
$mask = str_pad($mask, 16, "\x00"); // Pad to full 16-byte length | |
return $mask; | |
} | |
} | |
// example | |
var_dump(IPUtilities::IsInIPv4Range("127.0.0.1", "127.0.0.0/8")); // true | |
var_dump(IPUtilities::IsIpv6InSubnet("fe80::1", "fe80::", 10)); // true | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment