You are here

public static function CleantalkHelper::ip_mask_match in Anti Spam by CleanTalk 7.4

Same name and namespace in other branches
  1. 7.5 src/CleantalkHelper.php \CleantalkHelper::ip_mask_match()
2 calls to CleantalkHelper::ip_mask_match()
CleantalkHelper::ip_get in src/CleantalkHelper.php
CleantalkHelper::ip_is_private_network in src/CleantalkHelper.php

File

src/CleantalkHelper.php, line 167

Class

CleantalkHelper
Cleantalk's hepler class

Code

public static function ip_mask_match($ip, $cidr, $ip_type = 'v4', $xtet_count = 0) {
  if (is_array($cidr)) {
    foreach ($cidr as $curr_mask) {
      if (self::ip_mask_match($ip, $curr_mask, $ip_type)) {
        return true;
      }
    }
    unset($curr_mask);
    return false;
  }
  if ($ip_type == 'v4') {
    $xtet_base = 8;
  }
  if ($ip_type == 'v6') {
    $xtet_base = 16;
  }

  // Calculate mask
  $exploded = explode('/', $cidr);
  $net_ip = $exploded[0];
  $mask = $exploded[1];

  // Exit condition
  $xtet_end = ceil($mask / $xtet_base);
  if ($xtet_count == $xtet_end) {
    return true;
  }

  // Lenght of bits for comparsion
  $mask = $mask - $xtet_base * $xtet_count >= $xtet_base ? $xtet_base : $mask - $xtet_base * $xtet_count;

  // Explode by octets/hextets from IP and Net
  $net_ip_xtets = explode($ip_type == 'v4' ? '.' : ':', $net_ip);
  $ip_xtets = explode($ip_type == 'v4' ? '.' : ':', $ip);

  // Standartizing. Getting current octets/hextets. Adding leading zeros.
  $net_xtet = str_pad(decbin($ip_type == 'v4' ? $net_ip_xtets[$xtet_count] : hexdec($net_ip_xtets[$xtet_count])), $xtet_base, 0, STR_PAD_LEFT);
  $ip_xtet = str_pad(decbin($ip_type == 'v4' ? $ip_xtets[$xtet_count] : hexdec($ip_xtets[$xtet_count])), $xtet_base, 0, STR_PAD_LEFT);

  // Comparing bit by bit
  for ($i = 0, $result = true; $mask != 0; $mask--, $i++) {
    if ($ip_xtet[$i] != $net_xtet[$i]) {
      $result = false;
      break;
    }
  }

  // Recursing. Moving to next octet/hextet.
  if ($result) {
    $result = self::ip_mask_match($ip, $cidr, $ip_type, $xtet_count + 1);
  }
  return $result;
}