I'm looking for quick/simple method for matching a given IP4 dotted quad IP to a CIDR notation mask.

I have a bunch of IPs I need to see if they match a range of IPs.

example:

```\$ips = array('10.2.1.100', '10.2.1.101', '10.5.1.100', '1.2.3.4');

foreach (\$ips as \$IP) {
if (cidr_match(\$IP, '10.2.0.0/16') == true) {
print "you're in the 10.2 subnet\n";
}
}
```

What would cidr_match() look like?

It doesn't really have to be simple, but fast would be good. Anything that uses only built-in/common functions is a bonus (as I'm likely to get one person to show me something in pear that does this, but I can't depend on pear or that package being installed where my code is deployed).

Nov 6, 2020 in PHP 2,856 views

## 1 answer to this question.

Hello @kartik,

If only using IPv4:

• use ip2long() to convert the IPs and the subnet range into long integers
• convert the /xx into a subnet mask
• do a bitwise 'and' (i.e. ip & mask)' and check that that 'result = subnet'

something like this should work:

```function cidr_match(\$ip, \$range)
{
list (\$subnet, \$bits) = explode('/', \$range);
if (\$bits === null) {
\$bits = 32;
}
\$ip = ip2long(\$ip);
\$subnet = ip2long(\$subnet);
\$mask = -1 << (32 - \$bits);
\$subnet &= \$mask; # nb: in case the supplied subnet wasn't correctly aligned
return (\$ip & \$mask) == \$subnet;
}```

Hope it helps!!

• 82,880 points

## How to convert an array to a string in PHP?

What can I do to get the ...READ MORE

## How to convert a string to an array in php

I want to convert a string into ...READ MORE

## How to sort an array of associative arrays by value of a given key in PHP?

Given this array: \$inventory = array( ...READ MORE

## How to get the client IP address in PHP ?

Hello, Here is a code sample of a good ...READ MORE

+1 vote

## How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

## What is redirection in Laravel?

Named route is used to give specific ...READ MORE

## How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

+1 vote

## What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE