Ключи команды ping и примеры ее использования
Мы рассмотрим использование команды ping для Windows и, немного, для Linux.
Параметры команды ping и их описание
В зависимости от используемой операционной системы опции команды будут иметь разные назначения. Поэтому, если мы хотим понять все возможности, стоит ознакомиться с опцией help.
Общий синтаксис
Независимо от системы, команду ping можно применять так:
ping [опции] <имя сервера или IP-адрес>
Windows
Для просмотра в Windows также используйте команду ping /?
| Параметр | Описание |
|---|---|
| -t | Команда будет отправлять запросы на проверку постоянно, пока ее не прервать клавишами Ctrl + C. Удобно, если сеть не работает и чтобы постоянно не проверять, появилась ли связь. |
| -a | Пытается определить имя узла через DNS. |
| -n | Задает определенное число попыток отправки запроса. |
| -l | Размер пакета. Используется для проверки стабильности сети, создания тестовой нагрузки и так далее. |
| -f | По умолчанию ping разрешает фрагментацию, то есть пакет может быть разбит на несколько для соответствия минимальному пропускаемому размеру (MTU). Данный флаг это запрещает. Используется для определения вышеупомянутого MTU. |
| -i | Задает срок жизни пакета (количество сетевых устройств, через которые может пройти сигнал). Может использоваться в случаях, когда количество оборудования слишком велико. Также можно определить его количества. |
| -w | Устанавливает время ожидания. Применяется, если существуют проблемы производительности на сети или расстояние до узла очень большое. |
| -S | Позволяет выполнить проверку сети с определенного источника. Может быть использовано с узла с несколькими сетевыми адаптерами и отправкой запроса с определенного. |
| -4 | Использовать только IPv4. |
| -6 | Использовать только IPv6. |
| Параметр | Описание |
|---|---|
| -r | Записывает маршрут для указанного числа прыжков. |
| -s | Задает метку времени для указанного числа прыжков. |
| -j | Задает свободный выбор маршрута по списку узлов. |
| -k | Задает жесткий выбор маршрута по списку узлов. |
| -R | Использует заголовок маршрута для проверки и обратного маршрута. |
Linux
При минимальной инсталляциии данной системы или использовании docker, утилиты ping может не быть. В таком случае мы увидим ошибку:
bash: ping: command not found
Для ее установки можно воспользоваться менеджером установки пакетов. В зависимости от типа операционной системы, наши команды будут немного отличаться.
а) для систем на базе deb (Debian, Ubuntu, Mint):
apt install iputils-ping
б) для систем на базе RPM (Rocky Linux, CentOS, Red Hat, Fedora):
yum install iputils
Готово, теперь можно пользоваться командой ping.
Список ключей можно посмотреть так:
Примеры использования
Простой пример использования команды ping
Примерный ответ с исправной связью:
Обмен пакетами с yahoo.com [206.190.36.45] с 32 байтами данных:
Ответ от 206.190.36.45: число байт=32 время=191мс TTL=47
Ответ от 206.190.36.45: число байт=32 время=191мс TTL=47
Пример ответа, если узел недоступен:
Обмен пакетами с yahoo.com [206.190.36.45] по с 32 байтами данных:
Превышен интервал ожидания для запроса.
Превышен интервал ожидания для запроса.
* до удаленного узла нет сигнала. Возможно, существуют неполадки на сети.
При проверке связи не удалось обнаружить узел
Проверьте имя узла и повторите попытку.
* не удалось определить имя узла. Возможные неполадки: нет связи с DNS, не работает DNS, запрашиваемого имени узла не существует.
В Linux при отсутствии ответа, мы ничего не увидим, но если нам нужно видеть неудачные попытки, то используем ping с опцией -O:
ping -O 206.190.36.45
Открытие порта для Ping
Справедливо заметить, что не во всех случаях отсутствие ответа на ping означает, что удаленный узел недоступен. Администратор ресурса может намеренно отключить ответы на эхо-запросы.
Также важно знать, что ping не использует конкретный номер порта. Чтобы открыть возможность пинга, необходимо либо найти соответствующую опцию (во многих домашних роутерах) или разрешить ICMP (Internet Control Message Protocol) на брандмауэре. Ну, или наоборот — чтобы закрыть возможность пинга, блокируем запросы ICMP.
Проверка портов
С помощью команды ping нельзя проверить открытость того или иного порта.
Для этих целей используется команда telnet или программа, например, nmap.
How to ping IP and port from Windows or Linux
Ping IP and port from Windows and Linux machines
One of the things I do the most when troubleshooting deployments of services exposing data to the internet is pinging the IP and port where the service is supposed to be alive. In this tutorial, I will show you how to ping IP and port on Linux and Windows.
I think most system administrators know the commands for this, but if you like me normally don’t work like an IT admin (at least not anymore) I tend to forget the commands. Due to that, I have written this article as a reference for myself but also for everyone else, who is in need of pinging services they expect at a location.
Often it’s enough to just ping an IP to validate that you got “life” on the server. However if you like me often got many services running on one server (often when using Docker), I need to ping the specific port number on the server. One of the Kubernetes clusters I manage is running more than 100 services and here I use it a lot.
In this article/reference post, I will show you how to ping IP and port on your Windows or Linux machine using different commands in the terminal (CLI).
Ping IP and port using Telnet
This is my favorite when working on both Windows and Linux. I also think that it’s the easiest one to use and it’s called Telnet. You can with a simple command using Telnet ping IP and port on the remote server you would like to check.
Wikimedia Foundation, Inc. Contributors to Wikimedia projects
If you want to, you can also use a domain instead of the IP. A domain is often easier for humans to remember instead of numbers to multiple different servers locally or externally.
Below are the commands to ping IP and port on a server using Telnet:
As I mentioned above, you can use Telnet on both Windows and Linux computers/servers which makes it a great choice for most sys-ops.
On most computers, telnet is not installed by default. If you get the annoying error “telnet: command not found”, you have to install Telnet on the machine using the commands below:
Install Telnet on Linux
If you are working on a Linux Server or Desktop, you can use the below command to install Telnet on that machine:
Install Telnet on Windows
By default, Telnet is not an enabled Windows Feature. If you run Telnet on your computer in a Command Prompt, you will get the following error: “Telnet is not recognized as an operable program or batch file.”. So – to install Telnet on Windows, you have to do the following:
- Click on Start.
- Select Control Panel.
- Choose Programs and Features.
- Click Turn Windows features on or off.
- Select the Telnet Client option.
- Click OK.
A dialog box appears to confirm installation when it’s done. The telnet command should now be available in your Command Prompt. Remember to restart your CMD window.
Ping IP and port with Telnet example
Let’s check out how Telnet works. This website is running at IP: 172.67.161.26 – this is the public IP address of the website to which the domain is mapped to.
By default, all requests are redirected to HTTPS (port 443) if a request is made at port 80. This means that the server accepts connections on port 80 too – let’s try and ping both ports:
That went well. We got connected and could see that the server is responding on both ports. This simply means that the service on the port is up and running.
If you would like to escape out of the Telnet utility when connected, you can use “CTRL + ] ” or the “q” command.
Ping IP and port using Nmap
Another well-used tool is Nmap. In Nmap, you can ping a port by using the “-p” option including the IP or domain you would like to scan.
Free Security Scanner
A heads up – be aware of legal issues!
“When used properly, Nmap helps protect your network from invaders. But when used improperly, Nmap can (in rare cases) get you sued, fired, expelled, jailed, or banned by your ISP.” – Nmap website.
If you get an error telling you that Nmap is not available on your computer/server, you would have to install it.
Install Nmap on Linux
To install Nmap on your Linux machine, you can use the below command:
Install Nmap on Windows
Not as simple as Linux, but it’s still easy to use the official installer from Nmap’s website. Go to this page: Download Nmap and look under the Windows Binaries for the latest available installer file.
Once the installer has completed installing, you are now ready to use Nmap on your Windows computer.
Ping IP and port using Nmap
Let’s try to ping a website at IP “172.67.161.26” on the global internet at the default HTTPS port – 443. If you test this yourself, then don’t use that IP. Cloudflare is protecting the website and will block your access and in the worst-case ban your IP from their global network. Only do this at IPs you own or services that won’t do any damage to others.
Well, once again the port is returned as open on the server. This means that there is a service accepting data at port 443, which was just verified by Nmap.
Ping IP and port using PowerShell
Normally when I’m not on my own machines, which means I’m working on production servers not related to my own business/platform and it’s a Windows Server Environment, I always use PowerShell to ping IP and port.
A great thing about PowerShell is that you can use the methods in scripts running automated stuff in the background or during the setup of service or multiple services. A great thing if deploying with PowerShell would be to check if the ports were active after deployment and return a status to the terminal.
In PowerShell, we got something called Test-NetConnection which is a command where you specify either an IP or a domain followed by the port you would like to ping.
Below is an example of what this would look like on a local network:
In the test above you can see that the TCP call to my gateway at home succeeded at port 80. If you can’t get through to the service you will status False in TcpTestSucceeded.
Summary
In this quick article on how to ping IP and port using different tools on Windows or Linux machines, we learned how we can use the terminal to check if a given port is open and accepting requests.
If you got any issues, questions, or suggestions, please let me know in the comments below. Happy pinging!
Проверка связи с определенным портом
Можно ли вы пинговать конкретный порт машины, и если да, то можете ли вы привести пример?
Ищу что-то вроде ping ip address portNum.
Ответ 1
Нельзя пинговать порты, так как Ping использует ICMP, который не имеет понятия о портах. Порты относятся к протоколам транспортного уровня, таким как TCP и UDP. Однако вы можете использовать nmap, чтобы узнать, открыты ли порты или нет.
nmap -p 80 example.com
Как уже упоминалось, nmap — это больше, чем просто пинг-для-портов. Это лучший друг аудиторов и хакеров, который предлагает массу интересных опций. Проверьте в документации все возможные флаги.
Ответ 2
Откройте сеанс telnet для определенного порта, например:
# telnet google.com 80
Trying 74.125.226.48.
Connected to google.com.
Escape character is ‘^]’.
Ответ 3
Если вы используете Windows с PowerShell v4 или новее, вы можете использовать модуль PowerShell test-netconnection:
Test-NetConnection <host> -port <port>
Ответ 4
$ nc -vz google.com 80
Connection to google.com 80 port [tcp/http] succeeded!
Ответ 5
Можно использовать PaPing:
http://code.google.com/p/paping
C:\>paping.exe www.google.com -p 80 -c 4
paping v1.5.1 — Copyright (c) 2010 Mike Lovell
Connecting to www.l.google.com [209.85.225.147] on TCP 80:
Connected to 209.85.225.147: time=24.00ms protocol=TCP port=80
Connected to 209.85.225.147: time=25.00ms protocol=TCP port=80
Connected to 209.85.225.147: time=24.00ms protocol=TCP port=80
Connected to 209.85.225.147: time=24.00ms protocol=TCP port=80
Connection statistics:
Attempted = 4, Connected = 4, Failed = 0 (0.00%)
Approximate connection times:
Minimum = 24.00ms, Maximum = 25.00ms, Average = 24.25ms
Ответ 6
Попробуйте curl команду, например:
$ curl host:port
Например:
$ curl -s localhost:80 >/dev/null && echo Success. || echo Fail.
Success.
Вышеупомянутая команда вернет Fail при ненулевых кодах статуса выхода. В некоторых конкретных случаях, таких как пустой или искаженный ответ.
Ответ 7
Нет, нельзя, потому что ping использует протокол ICMP , в котором даже нет понятия портов.
Ответ 8
Я нашел более простое решение с помощью PsPing:
psping 192.168.2.2:5000
Это часть Windows Sysinternals .
PsPing реализует функции Ping, TCP ping, измерение задержки и пропускной способности.
Ответ 9
В Linux вы можете использовать hping, он использует TCP, а не ICMP.
hping example.com -S -V -p 80
Ответ 10
Ping очень специфичен, но если вы хотите проверить, открыт ли порт или нет, и используете ли вы окно Windows, тогда PortQry — ваш друг.
Я использовал его только для тестирования контроллеров домена на предмет проблем с подключением, он сработал, поэтому должен сработать и у вас.
Ответ 11
Вот консольное приложение .NET:
static void Main(string[] args) <
string addressArgument = null, portArgument = null;
System.Net.Sockets.TcpClient tcpClient = null;
Try <
addressArgument = args[0];
portArgument = args[1];
int portNumber;
portNumber = Int32.Parse(portArgument);
tcpClient = new System.Net.Sockets.TcpClient();
tcpClient.ReceiveTimeout = tcpClient.SendTimeout = 2000;
IPAddress address;
if (IPAddress.TryParse(args[0], out address)) <
var endPoint = new System.Net.IPEndPoint(address, portNumber);
tcpClient.Connect(endPoint);
> else <
tcpClient.Connect(addressArgument, portNumber);
>
Console.WriteLine(«Port <0>is listening.», portArgument);
> catch (Exception e) <
if (e is SocketException || e is TimeoutException) <
Console.WriteLine(«Not listening on port <0>.», portArgument);
> else <
Console.WriteLine(«Usage:»);
Console.WriteLine(» portquery [host|ip] [port]»);
>
> finally <
if (tcpClient != null)
tcpClient.Close();
>
>
Ответ 12
Пример ниже находит, какие IP на VPN имеют открытый VNC/порт 5900 с клиентом, работающим на Windows 7.
Короткий скрипт Python (v2.6.6) для сканирования заданного списка IP и портов:
from socket import *
fTimeOutSec = 5.0
sNetworkAddress = ‘192.168.1’
aiHostAddresses = range(1,255)
aiPorts = [5900]
setdefaulttimeout(fTimeOutSec)
print «Запуск сканирования. «
for h in aiHostAddresses:
for p in aiPorts:
s = socket(AF_INET, SOCK_STREAM)
address = (‘%s.%d’ % (sNetworkAddress, h))
result = s.connect_ex((address,p))
if ( 0 == result ):
print «%s:%d — OPEN» % (address,p)
elif ( 10035 == result ):
# вышло время запроса — выход
else:
print «%s:%d — closed (%d)» % (address,p,result)
s.close()
print «Сканирование завершено.»
Запуск сканирования…
Возможный результат:
192.168.1.1:5900 — closed (10061)
192.168.1.7:5900 — closed (10061)
192.168.1.170:5900 — OPEN
192.168.1.170:5900 — closed (10061)
Сканирование завершено.
Четыре переменные в верхней части нужно будет изменить, чтобы они соответствовали таймауту сети, хостам и портам, которые необходимы. 5,0 секунд, на моей VPN, казалось, будет достаточно для стабильной работы, но не всегда давало точные результаты. В моей локальной сети 0,5 было более чем достаточно.
Ответ 13
В оболочке Bash вы можете использовать pseudo-device file TCP , например:
</dev/tcp/serverfault.com/80 && echo Port open || echo Port closed
Вот версия, реализующая тайм-аут в 1 секунду:
timeout 1 bash -c «</dev/tcp/serverfault.com/81» && echo Port open || echo Port closed
Ответ 14
Если вы используете операционную систему * nix, попробуйте установить и использовать «zenmap», это графический интерфейс для nmap и несколько полезных профилей сканирования, которые очень помогают новому пользователю.
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
How to Ping a Specific Port in Windows and Linux

Ping is one of the most fundamental tools when it comes to network troubleshooting. It allows you to quickly test whether a given service/port is responding or not. Due the lightweight nature of ICMP packets, it allows ping to quickly fetch useful information about a given system without sending a series of packets that would otherwise overwhelm the host (in some cases).
Although pinging an entire host can be useful for checking if a given host is up, it does not offer much information about if a target port is up.