Find whether a given IP exists in CIDR or not

codeigniter, php

Solution

OK, try following this 5 simple steps...

1. Store your CIDRs into array (read 'em from database; guess you know how to get this)

$cidrs = array(
  '192.168.1.20/27', 
  '192.168.0.10/32'
  );

2. Get user's IP (remote address)

$user_ip = $_SERVER['REMOTE_ADDR'];

3. Add this function

function IPvsCIDR($user_ip, $cidr) {
  $parts = explode('/', $cidr);
  $ipc = explode('.', $parts[0]);
  foreach ($ipc as &$v)
    $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
  $ipc = substr(join('', $ipc), 0, $parts[1]);
  $ipu = explode('.', $user_ip);
  foreach ($ipu as &$v)
    $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
  $ipu = substr(join('', $ipu), 0, $parts[1]);
  return $ipu == $ipc;
  }

4. Compare user's IP address against $cidrs

$validaddr = false;
foreach ($cidrs as $addr)
  if (IPvsCIDR($user_ip, $addr)) {
    $validaddr = true;
    break;
    } 

5. Decide what to do with user

if ($validaddr) {
  echo "CORRECT IP ADDRESS";
  }
else {
  echo "INCORRECT IP ADDRESS";
  }

That's it!

how this function works. It converts CIDR address-part (x.x.x.x) into binary string and takes first N digits. Then it does same job with user's IP and checks do values match.

Example 2 (complete job from function)

function testUserIP($user_ip, $cidrs) {
  $ipu = explode('.', $user_ip);
  foreach ($ipu as &$v)
    $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
  $ipu = join('', $ipu);
  $res = false;
  foreach ($cidrs as $cidr) {
    $parts = explode('/', $cidr);
    $ipc = explode('.', $parts[0]);
    foreach ($ipc as &$v) $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
    $ipc = substr(join('', $ipc), 0, $parts[1]);
    $ipux = substr($ipu, 0, $parts[1]);
    $res = ($ipc === $ipux);
    if ($res) break;
    }
  return $res;
  }

Usage:

$user_ip = $_SERVER['REMOTE_ADDR'];
$cidrs = array('192.168.1.20/27', '192.168.0.10/32'); 
if (testUserIP($user_ip, $cidrs)) {
  // user ip is ok
  }
else {
  // access denied
  }

Problem

I am getting the IP address of a user using $_SERVER['REMOTE_ADDR'] who tries to visit my site. I have different boxes with different IDS and different CIDR entries in my database for each box. I want to check if the user IP exists in any of the CIDR or not for a specific box. If it exists then he is allowed to enter otherwise not. let suppose the user IP is ``` 127.0.0.1 ``` suppose The CIDR entries for box 12 is ``` 192.168.1.20/27 192.168.0.10/32 ``` The CIDR entries are stored in a column in database if he come with an IP that comes inside this range then he should be allowed to enter the site otherwise not. I want to check his ip against each CIDR entry. Any ideas please? Thanks

Original source

Related problems