/** * Is this IP in the same subnet as the supplied address? * * Accepts net masks for both IPV4 and IPV6 and will select the appropriate one, to * allow checking policy against request input with minimal method calls. * * @param string $matchIp presentation form ip address to compare * @param int $netMask4 network mask, bits to match <= 32 for IPV4 * @param int $netMask6 network mask, bits to match <=128 for IPV6 * * @return bool true if $this->ip and $matchIp are both in the specified subnet */ public function sameSubnet($matchIp, $netMask4, $netMask6) { $match = new IPAddress($matchIp); if (false === $this->ipVersion() || $this->ipVersion() !== $match->ipVersion()) { return false; } switch ($this->ipVersion()) { case 4: $mask = -1 << 32 - $netMask4; return (ip2long($this->ip) & $mask) === (ip2long($match->asReadable()) & $mask); break; case 6: $ipBits = $this->asBinaryString($this); $matchBits = $this->asBinaryString($match); $match = 0 === strncmp($ipBits, $matchBits, $netMask6); return $match; break; } return false; }