note 9546 deleted from function.ip2long by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: jna at retina dot net 

----

One thing PHP lacks is a way to compare two IP addresses, which I thought might be under this function, but isn't. Here goes:


function testip($range,$ip) {
  $result = 1;

  # IP Pattern Matcher
  # J.Adams <[email protected]>
  #
  # Matches:
  #
  # xxx.xxx.xxx.xxx        (exact)
  # xxx.xxx.xxx.[yyy-zzz]  (range)
  # xxx.xxx.xxx.xxx/nn     (nn = # bits, cisco style -- i.e. /24 = class C)
  #
  # Does not match:
  # xxx.xxx.xxx.xx[yyy-zzz]  (range, partial octets not supported)


  if (ereg("([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)",$range,$regs)) {

      # perform a mask match
      $ipl = ip2long($ip);
      $rangel = ip2long($regs[1] . "." . $regs[2] . "." . $regs[3] . "." . $regs[4]);

      $maskl = 0;

      for ($i = 0; $i< 31; $i++) {
          if ($i < $regs[5]-1) {
              $maskl = $maskl + pow(2,(30-$i));
          }
      }

      if (($maskl & $rangel) == ($maskl & $ipl)) {
          return 1;
      } else {
          return 0;
      }
   } else {

      # range based
      $maskocts = split("\.",$range);
      $ipocts = split("\.",$ip);

      # perform a range match
      for ($i=0; $i<4; $i++) {
          if (ereg("\[([0-9]+)\-([0-9]+)\]",$maskocts[$i],$regs)) {
            if ( ($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) {
                  $result = 0;
              }
          }
          else
          {
              if ($maskocts[$i] <> $ipocts[$i]) {
                  $result = 0;
              }
          }
      }
  }
  return $result;
}
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.