geoip_isp_by_name
Функция geoip_isp_by_name() возвращает имя интернет-провайдера (ISP) указанного IP-адреса.
Эта функция доступна только для тех, кто приобрёл коммерческую версию GeoIP ISP. Если такая база отсутствует, выводится предупреждение.
Список параметров
Имя хоста или IP-адрес.
Возвращаемые значения
Возвращает имя ISP в случае успешного выполнения или false , если адрес не найден в базе данных.
Примеры
Пример #1 Пример использования geoip_isp_by_name()
Выведет имя ISP для хоста example.com.
$isp = geoip_isp_by_name ( ‘www.example.com’ );
if ( $isp ) echo ‘Этот IP-адрес управляется провайдером: ‘ . $isp ;
>
?>?php
Результат выполнения данного примера:
Адрес управляется провайдером: ICANN c/o Internet Assigned Numbers Authority
User Contributed Notes
There are no user contributed notes for this page.
- Функции GeoIP
- geoip_asnum_by_name
- geoip_continent_code_by_name
- geoip_country_code_by_name
- geoip_country_code3_by_name
- geoip_country_name_by_name
- geoip_database_info
- geoip_db_avail
- geoip_db_filename
- geoip_db_get_all_info
- geoip_domain_by_name
- geoip_id_by_name
- geoip_isp_by_name
- geoip_netspeedcell_by_name
- geoip_org_by_name
- geoip_record_by_name
- geoip_region_by_name
- geoip_region_name_by_code
- geoip_setup_custom_directory
- geoip_time_zone_by_country_and_region
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
PHP проверка IP на вхождение в диапазон
Наверняка перед многими web-мастерами вставала задача — определить по маске подсети вхождение IP-адреса посетителя сайта. Цели при этом могут быть разными: выдать содержимое на странице в зависимости от географической принадлежности посетителя (что арабу хорошо, то еврею смерть), заблокировать доступ к сайту по IP… Впрочем, блокировать доступ к сайту удобнее с помощью файла .htaccess.
В общем, однажды подобная задача встала и передо мной — нужно было телефон на странице выводить в зависимости от страны посетителя сайта. Хождение по Google мало что дало. На многих блогах и форумах я находил какие-то обрезки php-скриптов, в большинстве своем не работающие. А если и попадались работающие скрипты, то проверка производилась только по одному диапазону IP-адресов. Пришлось писать свой php-код, коим и хочу поделиться.
В файл ipbase.txt вносим подсети IP-адресов нужной страны, берем их здесь: ipdeny.com →
// Функция проверки вхождения IP-адреса в подсеть:
$ip = $_SERVER[‘REMOTE_ADDR’];
function ip_in_net($ip, $net, $mask) // Преобразование IP в беззнаковое десятичное целое число:
$ip = (int)sprintf(«%u», ip2long($ip));
$mask = (int)sprintf(«%u», ip2long($mask));
$net = (int)sprintf(«%u», ip2long($net));
if (($ip & $mask) == $net) return 1;
>
else return 0;
>
>
// Поскольку подсети записаны в формате 127.0.0.0/8, то понадобится функция перевода CIDR в обычную маску: 127.0.0.0/255.0.0.0:
function cidr_to_mask($mask) return long2ip(pow(2, 32)-pow(2, (32-$mask)));
>
// Загружаем файл с базой подсетей, не забываем указать правильный путь к файлу:
$file = $_SERVER[‘DOCUMENT_ROOT’].’/ПУТЬ_К_ФАЙЛУ/ipbase.txt’;
// Если файл существует и доступен для чтения:
if (is_readable($file)) // Считываем файл в массив:
$nets = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Проходим массив циклом:
for($i = 0, $size = sizeof($nets); $i // Если строка существует:
if ($nets[$i]) // Разбиваем строку на массив, в качестве значений используются адрес и маска подсети:
$line = explode(‘/’, $nets[$i]);
$mask = cidr_to_mask($line[1]); // Переводим CIDR в обычную маску
$net = $line[0];
// Проверяем вхождение IP-адреса в подсеть:
if (ip_in_net($ip, $net, $mask)) // Если IP-адрес входит в подсеть, выводим результат:
echo ‘Адрес ‘.$ip.’ входит в подсеть ‘.$net.’/’.$mask;
// Или задаем значение переменной $ip для использования за пределами данного цикла (в правиле ниже):
$ip = ‘yes’;
break; // Прерываем цикл
>
>
>
>
?>?phpСкрипт удобнее разместить в отдельном файле, подключая его к нужной странице функцией include. Путь к файлу с базой подсетей также можно вынести из скрипта и прописывать на нужной странице. Так вы сможете использовать различные файлы для разных страниц, используя только один скрипт. При соответствии IP-адреса маске подсети в скрипте выводится только значение переменной $ip = ‘yes’, по которому на страницах сайта задаются определенные правила:
$file = $_SERVER[‘DOCUMENT_ROOT’].’/ПУТЬ_К_ФАЙЛУ/ipbase_egypt.txt’;
include($_SERVER[‘DOCUMENT_ROOT’].’/ПУТЬ_К_ФАЙЛУ/ipsearch.php’);
if ($ip == ‘yes’) // IP-адрес входит в подсеть, например, Египта, пишем приветствие для друзей-арабов:
echo ‘Рахат-лукум!’;
>
else // В противном случае приветствуем остальной мир, а арабы из Египта пусть идут руслом Нила — можно и в Крыму отдыхать, далась вам эта пустыня:
echo ‘Миру — мир, Крыму — Крым!’;
>
?>?phpНапоследок привожу оптимизированный код:
$file = $_SERVER[‘DOCUMENT_ROOT’].’/ПУТЬ_К_ФАЙЛУ‘;
if (is_readable($file)) $cidr = array(‘0.0.0.0’, ‘128.0.0.0’, ‘192.0.0.0’, ‘224.0.0.0’, ‘240.0.0.0’, ‘248.0.0.0’, ‘252.0.0.0’, ‘254.0.0.0’, ‘255.0.0.0’, ‘255.128.0.0’, ‘255.192.0.0’, ‘255.224.0.0’, ‘255.240.0.0’, ‘255.248.0.0’, ‘255.252.0.0’, ‘255.254.0.0’, ‘255.255.0.0’, ‘255.255.128.0’, ‘255.255.192.0’, ‘255.255.224.0’, ‘255.255.240.0’, ‘255.255.248.0’, ‘255.255.252.0’, ‘255.255.254.0’, ‘255.255.255.0’, ‘255.255.255.128’, ‘255.255.255.192’, ‘255.255.255.224’, ‘255.255.255.240’, ‘255.255.255.248’, ‘255.255.255.252’, ‘255.255.255.254’, ‘255.255.255.255’);
$ip = intval(sprintf(«%u», ip2long($_SERVER[‘REMOTE_ADDR’])));
$nets = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
for($i = 0, $size = sizeof($nets); $i // Маркер вхождения $ip в подсеть $net/$mask
break;
>
unset($line, $mask, $net);
>
>
unset($cidr, $ip, $nets, $i, $size);
>
unset($file);?php
if (!empty($mark)) // Адрес $ip входит в подсеть $net/$mask
>
?>Запрещается републикация статьи без указания активной прямой ссылки на источник.
За помощью в решении различных задач по программированию на языках PHP, JavaScript (включая jQuery) обращайтесь через раздел «Контакты» .Записки программиста
- Динамическая таблица PHP
- Защита почты от спама
- Защита сайта — запрет доступа к сайту по IP-адресам стран, защита сайта от спам-ботов, защита сайта от хакеров
- Защита сайта от ботов по User Agent
- Защита сайта от парсинга
- О говносайтах и плагиате
- Подмена User Agent Opera
- Сетевой экран Kaspersky Endpoint Security 11
- Список доменных зон
Проверить IP адрес
Чтобы узнать информацию по IP — введите IP-адрес и нажмите кнопку проверить.
Инструменты
- Whois сервис
- Массовый Whois
- Регистрация домена
- Punycode конвертация
- Проверить IP
- Ответ сервера
- Проверить ИКС сайта
- Информер ИКС
- CHMOD калькулятор
Используйте промокод от REG.RU для получения 5% скидки на домены и хостинг!
- Новости о доменах
- Статьи о доменах
- FAQ по доменам
- Полезные ссылки
- Словари и списки
- Программы
- Скрипты
- Прочее
Cервиcы сайта позволят проверить домен на занятость, получить регистрационную информацию по домену, подобрать домен для блога или сайта. На сайте вы сможете конвертировать домен в Punycode, проверить IP-адрес, узнать тИЦ и PR для сайта.
© 2008 — 2023 White Whois. Использование материалов сайта возможно только при указании ссылки на сайт.
What Is My IP?
An IP (Internet Protocol) address is a uniquely-identifying string of numbers assigned to each Internet-connected device or any device connected to a network. The address identifies and allows these devices to communicate with each other, either on an internal or external computer network.
Any device that transmits or receives network traffic gets an IP. 192.168.10.1 is an IP address example; any device with that IP can communicate with other devices across the same network. All governing devices, whether DHCP server, router, or Internet service provider, all use some sort of IP address management (IPAM) to prevent the assignment of the same Internet Protocol address to multiple devices. When there exists two devices with the same IP on the same network, an IP conflict prevents data from correct transmission and reception on these devices.
Your Internet activity then goes through your Internet service provider and routes back to you via the IP address assigned to you. Your address isn’t permanent, though; it can change based onyour connection and the network you choose to connect to. It works, theoretically, as a digital version of your home address. It’s like how you need a home address to receive mail, and the sender must have your correct home number and zip code; you need an Internet Protocol addressto connect to the Internet, and any device trying to connect to yours needs the proper IP for asuccessful connection.
An IP can indicate which Internet service provider you use and your Internet speed. It also reveals information about your general location. It could indicate your country, state, city, orpostal region. However, you can’t find someone’s exact location from their IP. The information is intended for other devices and networks to identify your device, not for others to track you down.
What is a private IP address?
A private IP address is an IP assigned to devices on private networks. These types of IPs, also referred to as local IP addresses or internal IP addresses, are used on local area networks (LANs) like your home network. They usually begin with 10, 172, or 192, which are in classes A, B, and C, respectively. These blocks are reserved for private IP addresses only by the Internet Assigned Numbers Authority (IANA).
There are two types of IP addresses: IPv4 and IPv6. Originally, private IP addresses were created to help delay the exhaustion of IPv4 addresses, as there is a limited number of IPv4 addresses. But even with the theoretical 4,294,967,296 addresses created by the 32-bit system, IPv4 address space began to run low with the amount of new Internet-connected devices that came into businesses and homes.
Thus, private IP addresses allow private networks to use the same IP addresses internally without causing conflicts for public IP addresses. Though IPv6 addresses ended up being the solution to IPv4 exhaustion, the private IP address system still exists for internal networks.
How do I find my IP address?
Our homepage shows you your public IP address above. You’ll see the IPv4 and, if available, the IPv6 assigned by your Internet service provider (ISP). Your public IP address is the IP that is logged when you visit websites or use any other services on the Internet. It differs from your private IP address, which varies by individual device as each device is assigned a private IP address.
If you want to find your private IP address on another device, like your phone or computer, you can follow our guides.
What is my local or private IP address?
Your local or private IP address is assigned to your device, typically by your router. The router assigns local IP addresses to devices on a network that connect to WiFi. Because of this, your private IP address will vary by device and by network.
The homepage shows your public IP address, but if you want to find your private IP address, you can follow our guides below.
Can you find the location of an IP address?
Yes, you can find the location of an IP address in most cases. However, the location may not always be accurate. Locational data for IP address geolocation varies based on the database. Though the information is generally accurate at pinpointing an IP’s country and city, it can’t tell you an exact street address.
Essentially, the accuracy decreases as the map narrows; an IP location search can bring up the continent, country, city, zip code, and time zone of an address, but it can’t get more specific than that. If you need to find someone’s exact address, looking up their location may not get you as far as you need to go.
Use the IP address lookup tool to gather location information about an IP address.
Can I be found if someone has my IP address?
In short, no – you don’t need to worry about your exact location being found through your IP address. Though IP addresses, by design, can be tracked, the purpose is to indicate your location to Internet service providers and other devices when you’re accessing the Internet. Without this service, they wouldn’t be able to serve their purpose. However, this doesn’t mean that someone can track you by your IP address.
If someone was able to get your IP address, they could learn a bit about your Internet service, such as which provider you use to connect to the Internet, but they really can’t locate you, your home, or your office. Your IP address doesn’t contain the information necessary to reveal your exact physical location to anyone who may attempt to trace your IP address and find you. In some circumstances, a person may be able to locate the city or general area you’re in. But they can’t get your physical address; though your IP address links to a geographical location, it’s not specific enough to find you. Anyone tracing your IP address could only get to your Internet service provider.
If you want to know how to find someone with IP address information, you’ll still find helpful data from the address. An IP address does contain some geographical location information. In some cases, an IP address indicates the country, state, city, or zip code where a device is located. It also tells others the identity of your ISP. However, even with that information, your IP address doesn’t reveal enough to pinpoint your location, your personal information, or put you in any danger.
Find IP Address Location
Use this IP address lookup tool to find the location of any IP address. Get details such as the originating city, state/region, postal/zip code, country name, ISP, and time zone.
How to Change My IP Address
Changing your IP address provides additional online privacy. Understand how a VPN, a proxy, or your router can give you a different IP on any of your devices.
How to Trace an Email Address
Learn how to trace an email address to avoid spam, block fake emails, and trace malicious messages. Follow a few short steps in this guide to trace emails in your email client.
Protect Your Personal Information Online
Learn how to recognize those security issues that may be making you vulnerable online.
Find Someone Online for Free
Learn to find someone online using free tools. Whether you have their name, phone number, username, email address or IP address, this tutorial will guide you step by step.
Reasons to Use a VPN
Learn how a VPN can prevent others from spying on you and viewing your sensitive data while you search.
What Is DNS?
DNS translates IP addresses into domain names for simple Internet navigation. Learn what DNS is, how it works, and fix common issues.
What Is a VPN?
A VPN is an encryption method that adds security and privacy to any network connection. Learn how to secure your data with a VPN.
What Is a Proxy?
A proxy helps you hide your IP address and gain anonymity online. Learn to find your proxy address or set up a new proxy in popular browsers.
Online Privacy Checklist
Check your online privacy practices. Learn how private browsers, HTTPS sites, and social media settings can keep you safe on the Internet.
- Do Not Sell My Personal Information
- Change Consent
