📄 Source: net.php
<?php
/**
* Tiny network helpers: LAN detection, client IP.
*/
function client_ip(): string {
// PHP built-in server sets REMOTE_ADDR reliably. Behind a proxy,
// you'd also check X-Forwarded-For, but we deliberately don't trust it
// by default (spoofable).
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
function ip_in_cidr(string $ip, string $cidr): bool {
if (strpos($cidr, '/') === false) {
return $ip === $cidr;
}
[$subnet, $bits] = explode('/', $cidr, 2);
$bits = (int)$bits;
$ip_long = ip2long($ip);
$subnet_long = ip2long($subnet);
if ($ip_long === false || $subnet_long === false) {
return false;
}
if ($bits < 0 || $bits > 32) {
return false;
}
$mask = $bits === 0 ? 0 : (~0 << (32 - $bits));
return ($ip_long & $mask) === ($subnet_long & $mask);
}
function is_lan(array $subnets): bool {
$ip = client_ip();
foreach ($subnets as $cidr) {
if (ip_in_cidr($ip, $cidr)) {
return true;
}
}
return false;
}
← Back