function test_fbBinarySearch_File_1() { $ips = array('0.0.0.0' => "000.000.000.000\t000.255.255.255\tUS", '10.0.0.1' => "010.000.000.000\t010.255.255.255\tI0", '10.255.255.255' => "010.000.000.000\t010.255.255.255\tI0", '127.0.0.1' => "127.000.000.000\t127.255.255.255\tL0", '127.0.0.2' => "127.000.000.000\t127.255.255.255\tL0", '127.255.255.255' => "127.000.000.000\t127.255.255.255\tL0", '172.16.0.0' => "172.016.000.000\t172.031.255.255\tI0", '172.31.255.255' => "172.016.000.000\t172.031.255.255\tI0", '192.168.0.0' => "192.168.000.000\t192.168.255.255\tI0", '192.168.0.1' => "192.168.000.000\t192.168.255.255\tI0", '192.168.255.255' => "192.168.000.000\t192.168.255.255\tI0", '255.0.0.0' => "221.097.211.000\t255.255.255.254\tUS", '255.255.255.254' => "221.097.211.000\t255.255.255.254\tUS", '255.255.255.255' => "255.255.255.255\t255.255.255.255\t--"); foreach ($ips as $ip => $expected) { $ipf = fbGeoIP_Free_Ascii::_formatIP4address($ip); $bsf =& new fbBinarySearch_File($this->_file); $rv = $bsf->search($ipf); $rv = trim($rv); $this->assertEquals($expected, $rv, "ip='{$ip}' ipf='{$ipf}' gettype(expected)=" . gettype($expected) . ' gettype(rv)=' . gettype($rv)); } }
function getCountryIdByIP($ip) { static $cache = array(); $ipf = fbGeoIP_Free_Ascii::_formatIP4address($ip); if (!$ipf) { return false; } /* if (isset($cache[$ipf])) { return $cache[$ipf]; } */ // \todo make a parameter $file = FREEBEER_BASE . '/etc/geo/geo-ips.txt'; if (!is_file($file)) { trigger_error(sprintf("File not found: '%s'", $file)); return false; } $bsf =& new fbBinarySearch_File($file); $bsf->setReadLength(64); // 36 for unix, 37 for ms-dos/windows $found = $bsf->search($ipf); $midval = $bsf->getRecordNumber(); $rec_len = $bsf->getRecordLength(); if ($found === false) { return false; } fbDebug::log(sprintf("ip=%s found=%s midval=%s rec_len=%s\n\n", $ip, $found, $midval, $rec_len)); $matches = preg_split('/\\s+/', $found); if (count($matches) < 3) { trigger_error(sprintf('Read error reading \'%s\': File does not contain whitespace', $file)); return false; } if ($ipf < $matches[0] || $ipf > $matches[1]) { trigger_error(sprintf('Unexpected result: \'%s\' (\'%s\') is not between \'%s\' and \'%s\'', $ip, $ipf, $matches[0], $matches[1]), E_USER_NOTICE); return false; } // $cache[$ipf] = trim($matches[2]); return trim($matches[2]); }