mask = ((1<<($mask))-1) << (32 - $mask); $this->addr = ip2long($addr) & $this->mask; fprintf(STDERR, "New ipclass item: %x (%x)\n", $this->addr, $this->mask); } function match($ip) { // fprintf(STDERR, "IP: %x, ADDR: %x, MASK: %x -> (%d)\n", // $ip, $this->addr, $this->mask, ((ip2long($ip) & $this->mask) == $this->addr)); return (($ip & $this->mask) == $this->addr); } static function compare($a, $b) { if ($a->addr == $b->addr) return (0); return (($a->addr < $b->addr) ? -1 : 1); } } class IPClass { var $ipcl; function IPClass() { $this->ipcl = NULL; } static function create($ip_in=NULL) { $thiz = new IPClass(); if ($ip_in != NULL) $thiz->update($ip_in); return ($thiz); } function update($ip_in) { $this->clean(); $this->ipcl = array(); for ($i = 0 ; $i < count($ip_in) ; $i++) { $this->ipcl[$i] = new IPClassItem($ip_in[$i]); } usort($this->ipcl, array("IPClassItem", "compare")); } function clean() { if ($this->ipcl != NULL) { $ct = count($this->ipcl); for ($i = 0 ; $i < $ct ; $i++) { unset($this->ipcl[$i]); } $this->ipcl = NULL; } } function check($ip_str) { $ip = ip2long($ip_str); if (count($this->ipcl) == 0) { return (FALSE); } if ($ip < $this->ipcl[0]->addr) return (FALSE); $imin = 0; $imax = count($this->ipcl) - 1; while ($imax >= $imin) { $imid = intval($imin + (($imax - $imin) / 2)); // printf("X: %d M: %d N: %d | ", $arr[$imin], $arr[$imid], $arr[$imax]); if ($this->ipcl[$imid]->addr == $ip) { break; } else if ($this->ipcl[$imid]->addr > $ip) { $imax = $imid - 1; } else { $imin = $imid + 1; } } if ($this->ipcl[$imid]->addr > $ip) { if ($imid > 0) { $imid--; } else { $imid = -1; } } if ($imid > -1) { if ($this->ipcl[$imid]->match($ip)) { fprintf(STDERR, "ban_list[%d] = %x (%x) MATCH\n", $imid, $this->ipcl[$imid]->addr, $this->ipcl[$imid]->mask); return(TRUE); } } return (FALSE); } } ?>