Skip to content

Commit 6dc347a

Browse files
committed
minor #20082 [http-foundation] Check if ip is in cidr subnet (damienfern)
This PR was merged into the 5.4 branch. Discussion ---------- [http-foundation] Check if ip is in cidr subnet While I was searching a way to check if an IP is included in a CIDR subnet, I found this old stack overflow : https://stackoverflow.com/questions/594112/check-whether-or-not-a-cidr-subnet-contains-an-ip-address This old question has of course an old answer but also has a "recent" one that might answer to 99% use cases of Symfony devs. And should be in the documentation. Commits ------- 24a61bd docs(http-foundation): check if ip is in cidr subnet
2 parents f91bf7d + 24a61bd commit 6dc347a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

components/http_foundation.rst

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,27 @@ analysis purposes. Use the ``anonymize()`` method from the
353353
$anonymousIpv6 = IpUtils::anonymize($ipv6);
354354
// $anonymousIpv6 = '2a01:198:603:10::'
355355

356+
357+
Check if an IP belongs to a CIDR subnet
358+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
359+
360+
If you need to know if an IP address is included in a CIDR subnet, you can
361+
use the ``checkIp`` method from the
362+
:class:`Symfony\\Component\\HttpFoundation\\IpUtils` to do that::
363+
364+
use Symfony\Component\HttpFoundation\IpUtils;
365+
366+
$ipv4 = '192.168.1.56';
367+
$CIDRv4 = '192.168.1.0/16';
368+
$isIpInCIDRv4 = IpUtils::checkIp($ipv4, $CIDRv4);
369+
// $isIpInCIDRv4 = true
370+
371+
$ipv6 = '2001:db8:abcd:1234::1';
372+
$CIDRv6 = '2001:db8:abcd::/48';
373+
$isIpInCIDRv6 = IpUtils::checkIp($ipv6, $CIDRv6);
374+
// $isIpInCIDRv6 = true
375+
376+
356377
Accessing other Data
357378
~~~~~~~~~~~~~~~~~~~~
358379

0 commit comments

Comments
 (0)