<?
// Подключаемся к базе данных
$db_host = "localhost";
$db_user = "";
$db_password = "";
$db_database = "netload";
$link = mysql_connect ($db_host, $db_user, $db_password);
if ($link && mysql_select_db ($db_database)) {
    mysql_query ("set names utf8");
} else {
    die ("db error");
}

// Подключаем библиотеку технических функций
require_once ("./lib.php");

// IP-адрес, который нужно проверить
$ip = "95.135.158.249";

// Преобразуем IP в число
$int = ip2int($ip);

$country_name = "";
$country_id = 0;

$city_name = "";
$city_id = 0;

// Ищем по российским городам
$sql = "select * from (select * from net_ru where begin_ip<=$int order by begin_ip desc limit 1) as t where end_ip>=$int";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
    $sql = "select * from (select * from net_ru_2 where begin_ip<=$int order by begin_ip desc limit 1) as t where end_ip>=$int";
    $result = mysql_query($sql);
}
if ($row = mysql_fetch_array($result)) {
    $city_id = $row['city_id'];
    $sql = "select * from net_city where id='$city_id'";
    $result = mysql_query($sql);
    if ($row = mysql_fetch_array($result)) {
        $city_name = $row['name_ru'];
    }
    $country_id = 20;
    $country_name = "Россия";
} else {
    // Ищем страну
    $sql = "select * from (select * from net_country_ip where begin_ip<=$int order by begin_ip desc limit 1) as t where end_ip>=$int";
    $result = mysql_query($sql);
    if ($row = mysql_fetch_array($result)) {
        $country_id = $row['country_id'];
        $sql = "select * from net_country where id='$country_id'";
        $result = mysql_query($sql);
        if ($row = mysql_fetch_array($result)) {
            $country_name = $row['name_ru'];
        }
    }

    // Ищем город
    $city_name = "";
    $city_id = 0;
    // Ищем город в СНГ
    $sql = "select * from (select * from net_su where begin_ip<=$int order by begin_ip desc limit 1) as t where end_ip>=$int";
    $result = mysql_query($sql);
    // Ищем город в глобальной базе
    if (mysql_num_rows($result) == 0) {
        $sql = "select * from (select * from net_city_ip where begin_ip<=$int order by begin_ip desc limit 1) as t where end_ip>=$int";
        $result = mysql_query($sql);
    }
    if ($row = mysql_fetch_array($result)) {
        $city_id = $row['city_id'];
        $sql = "select * from net_city where id='$city_id'";
        $result = mysql_query($sql);
        if ($row = mysql_fetch_array($result)) {
            $city_name = $row['name_ru'];
        }
    }
}

// Выводим результат поиска

if ($country_id == 0) {
    echo "Страна не определена";
} else {
    echo $country_id." ".$country_name;
}

echo "<br>";

if ($city_id == 0) {
    echo "Город не определен";
} else {
    echo $city_id." ".$city_name;
}

?>