mlocati/ip-lib

How to check two IPs are in the same subnet?

Closed this issue · 1 comments

Hello.

I need to ensure that two HTTP requests are from the same subnet (/16).
Couldn't figure out how to check this with your lib :(

My guess was to get rangeFromBoundaries from the first IP and compare it with matches($range) on the second IP. But rangeFromBoundaries second argument requires exact rage specification, I've tried different options, but with no luck...

And were doubts if this method will support ipv6 also...

This code should solve what you need:

use IPLib\Factory;

$ip1 = '192.168.1.127';
$ip2 = '192.168.0.1';

if (Factory::rangeFromString("{$ip1}/24")->contains(Factory::addressFromString($ip2))) {
    echo "{$ip1} and {$ip2} are in the same /24 subnet";
} else {
    echo "{$ip1} and {$ip2} are NOT in the same /24 subnet";
}

(and yes, it works both for IPv4 and IPv6)