A ping is a tool and command used to troubleshoot network and system-related problems. The ping command normally uses the ICMP protocol and make checks if the remote system is up or down without a TCP or UDP. The ping port is a term used to check a remote port which can be TCP or UDP if it is open and accessible. There are different tools that can be used to ping a TCP or UDP port. Telnet, nmap, putty, netcat,psping are some of them.
- The application can not connect database service.
- If the firewall has configured properly to allow or deny specific ports.
- Check if the remote SNMP service is running properly.
- Before attacking the remote port if the port is up and responding properly.
I’m trying to make a simple script on cmd (bat file) to check if couple of remote servers are up and up running
i wanted to ping a specific ip and port.
when i got %ERRORLEVEL% = 1 i knew there was a problem
and when i got %ERRORLEVEL% = 0 the server was ok
then i tried using telnet on my script and telnet dosent return any value (to what i could find) if there is a successful Session or not
if anyone got any other way to check if couple servers are running for a script i would appreciate the help.
Thanks

29 gold badges105 silver badges195 bronze badges
asked Nov 25, 2017 at 11:57
if you are using windows, why don’t you use PowerShell.
here is a sample code to ping to a specfic port
TNC -ComputerName SQLServer01 -Port 1433answered Nov 25, 2017 at 12:01

Panna Das
6 silver badges11 bronze badges
This is a fully working Batch file that gives “True” or “False” as result:
@echo off
setlocal
if "%~2" equ "" echo Usage: %0 ComputerName Port & goto :EOF
for /F "tokens=3" %%a in ('powershell TNC -ComputerName %~1 -Port %~2') do set "result=%%a"
echo %result%answered Nov 25, 2017 at 14:09

12 gold badges71 silver badges108 bronze badges
Test-NetConnection ip_address_here -p port_number_hereTest-NetConnection 10.0.0.53 -p 3006
29 gold badges105 silver badges195 bronze badges
answered Oct 10, 2021 at 8:59
5 silver badges8 bronze badges
first you should install telnet client
then press window+r and type cmd
command prompt open after that put a command telnet remoteIP port
answered Dec 8, 2017 at 8:08

The ping is a term and command-line tool used to check remote system network connectivity. It is one of the most popular tools for network diagnostics. By default, the usage of the ping command does not require any port number and will work with just a target IP address or domain name. But you may ask what port number is used by the ping command.
The TCP and UDP protocols are very popular where they can provide multiple port numbers to provide different services over the network. The ping command can be related to these TCP and UDP protocols but it does not use TCP or UDP. This may be even asked you in an interview or certificate exam or class exam. The ping command uses the ICMP protocol. The ping is an old method and tool described in the RFC792 and this standard does not provide any port number for the ping.
Ping and ICMP Protocol
The ping tool uses the ICMP protocol which is different from the TCP and UDP protocol where it is tightly integrated with the IP protocol. The ICMP is a layer 3 protocol that is transmitted with the IP packets even the IP is also a layer 3 protocol too. The ICMP is created to support the IP protocol.
Ping Uses ICMP Type 8 and Type 0
Ping Packet Content
$ ping 8.8.8.8

Is Port 7 Used For Ping ICMP?
Alternative Way Ping TCP Ports
Как проверить доступен ли порт сервера? Или внешний веб-сервис? Приведены несколько способов для использования на Windows-системах.
В процессе разворачивания и эксплуатации информационных систем часто требуется проверка доступности порта того или иного ресурса. Это может быть сервер приложений 1С, к которому не удается подключиться пользователю. Или же это внешний веб-ресурс, к которому происходит обращение. Или что-то еще.
Для проверки доступности самого сервера обычно используется команда ping. Но, в силу того, что данная утилита работает с ICMP-пакетами, для конкретного порта проверить доступ таким образом невозможно. Кроме того, на ресурсе в целях безопасности может быть заблокирован ответ на ICMP-пакеты, соответственно, результат доступности нельзя считать однозначным, если ресурс “не пингуется”.
Как проверить доступен ли порт?
Традиционный способ.
Первое, что приходит на ум – использовать “старый добрый” telnet.
Для примера проверять будем доступность менеджера кластера:
C:\>telnet ks-app-02 2141
Получили в ответ “кракозябру” – значит доступ есть

Microsoft Telnet> q
Загвоздка в том, что в большинстве современных Windows-систем telnet-клиент не установлен по-умолчанию, и требуется доустанавливать этот компонент. Что не всегда возможно, т.к. компьютер может быть и не своим и/или нет соответствующих прав.

Способ без инсталляции программ.
Хотелось бы иметь какой-то инструмент, не требующий установки, портабельный, чтобы можно было его просто скопировать и пользоваться, а при необходимости, легко удалить после использования.
В качестве такого инструмента удобно использовать утилиту psping от Sysinternals.
C:\>psping ks-app-02:2141

Еще один портабельный инструмент, позволяющий решить задачу:
C:\>tcping ks-app-02 2141

Встроенный инструментарий.
Однако есть возможность обойтись и совсем без сторонних утилит. В Windows есть встроенный инструмент, позволяющий выполнить такую проверку.
PS C:\> Test-NetConnection ks-app-02 -Port 2141

В ответе нас интересует последняя строка – TcpTestSucceeded: True. В данном случае – доступ есть.
Также, в ответе может содержаться еще значение PingSucceeded – это “обычный” ping по ICMP.
У командлета есть очень удобный для запоминания и быстрого ввода альяс tnc, а также ключ позволяющий ограничить вывод только результатом.
C:\>tnc ks-app-02 -Port 2141 -InformationLevel Quiet

Разумеется, запускать командлет необходимо в окне PowerShell, а не “командной строки”.
Хотя, из командной строки тоже можно, вызвав PowerShell:
C:\>powershell tnc ks-app-02 -port 2141
Следует заметить, что командлет доступен в версиях PowerShell от 4.0 и выше, т.е. начиная с Windows Server 2012 R2 и Windows 8.1
Заключение
Заметка не предполагает исчерпывающего списка и анализа всех возможных способов. Приведены три варианта, которые можно было бы охарактеризовать как “традиционный”, “портабельный” и “встроенный”. Каждый из них имеет свою область применения, в зависимости от системы, на которой необходимо выполнить проверку.
Полагаю, опытные администраторы смогут добавить еще несколько способов. Каким способом пользуетесь Вы и почему?
In this post, we will discuss how you can use various tools to send a ping request to check if a target port on a specific host is alive.
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.
Method 1 – Use Telnet
You are probably familiar with telnet. Also known as Terminal or Network, Telnet is a command-line utility that allows you perform interactive network communication using the TELNET protocol.
An telnet tutorial is coming up soo. Stay tuned for that.
To ping a specific port using telnet, use the command syntax as:
telnet [ip_address] [port_number]The telnet command is available in both Windows and Unix systems. However, you may need to enable Telnet in Windows.
To learn how do that, check the link below:
On macOS, use brew to install Telnet:
brew install telnetOn Debian and Debian-Based distributions, install telnet:
sudo apt-get install telnetThe example below shows how to use telnet to check if Nginx Server is running.
telnet 67.205.166.236 80If the service is running, telnet will connect and return an output as:
Trying 67.205.166.236...
Connected to 67.205.166.236.
Escape character is '^]'.Method 2 – Using Nmap
Start by installing nmap:
sudo apt-get install nmapbrew install nmapsudo yum install nmapOnce installed, check if a port is up by running the command:
nmap -p <port> [target_address]sudo nmap -p 80 67.205.166.236Nmap will return detailed information including the latency, port number, associated service and its state. An exmaple output is as shown:
Starting Nmap 7.93 ( https://nmap.org ) at 2022-10-02 10:49 EAT
Nmap scan report for 67.205.166.236
Host is up (0.28s latency).
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 0.65 secondsMethod 3 – Using Netcat
To ping a port using netcat, run the command:
nc -vz [target_address] [port_number]sudo nc -zv 67.205.166.236 80
Connection to 67.205.166.236 port 80 [tcp/http] succeeded!We can see that the connection to the target address and port is successful. This indicates the port/service is up.
Method 3 – Using cURL
We obviously cannot forget to mention cURL in this list. The command syntax is as shown:
curl -s [host:port]curl -s 67.205.166.236:80 >/dev/null && echo Connected. || echo Failed.The command should “Connected” if the port/service is up.
Method 4 – Using Windows PowerShell
In Windows, you can use the Test-NetConnection cmdlet to test if a port is up and running. The command syntax is as shown:
Test-NetConnection [ip_address] -p [port_number]Test-NetConnection 67.205.166.236 -p 80The command should return details about the target host and the connection status.
ComputerName : 67.205.166.236
RemoteAddress : 67.205.166.236
RemotePort : 80
InterfaceAlias : Ethernet
SourceAddress : 192.168.1.101
TcpTestSucceeded : TrueMethod 5 – Using PsPing Utility
In Windows, you can also use the PsPing utility which is part of Windows SysInternals tools. Download the tool in the resource below:
You can then use the command synax below to ping a specific port:
psping [address:port]psping.exe 67.205.166.236:80The command should send ping request to the target address and port and return the output as shown:
PsPing v2.10 - PsPing - ping, latency, bandwidth measurement utility
Copyright (C) 2012-2016 Mark Russinovich
Sysinternals - www.sysinternals.com
TCP connect to 67.205.166.236:80:
5 iterations (warmup 1) ping test:
Connecting to 67.205.166.236:80 (warmup): from 192.168.1.101:59835: 239.30ms
Connecting to 67.205.166.236:80: from 192.168.1.101:59837: 239.56ms
Connecting to 67.205.166.236:80: from 192.168.1.101:59838: 239.36ms
Connecting to 67.205.166.236:80: from 192.168.1.101:59839: 237.90ms
Connecting to 67.205.166.236:80: from 192.168.1.101:59842: 237.86ms
TCP connect statistics for 67.205.166.236:80: Sent = 4, Received = 4, Lost = 0 (0% loss), Minimum = 237.86ms, Maximum = 239.56ms, Average = 238.67msThe above port is up.
Conclusion
In this post, we explored various methods and tools you can use to ping a specific port in both Windows and Unix based systems.
Thanks for reading and catch you in the next one!!
If you enjoy our content, please consider buying us a coffee to support our work:

Способ 1: Утилита netstat
netstat — стандартная утилита, входящая в состав операционной системы Windows 10. Она применяется для отображения сетевой информации, в том числе и позволяет посмотреть список открытых портов. Благодаря этому можно узнать состояние, тип порта, локальный и внешний адрес. Этот вариант приоритетный, поскольку не требует перехода на разные сайты и скачивания дополнительного программного обеспечения, а о принципах взаимодействия с этой командой читайте в статье по ссылке ниже. Там также описаны и доступные аргументы, которые рекомендуется использовать, чтобы показать только интересующие сведения.
Подробнее: Использование команды netstat для просмотра открытых портов

Порты нужны определенным программам и службам для входящих подключений, поэтому они обязательно отслеживаются стандартным межсетевым экраном. Любое разрешение на открытие порта сохраняется в соответствующем списке, который можно использовать для выполнения поставленной задачи, что происходит так:
- Откройте «Пуск» и перейдите оттуда в меню брандмауэра.
- Через левую панель переместитесь к разделу «Дополнительные параметры».
- Откройте директорию «Правила для входящих подключений».
- Отыщите любое разрешающее подключение и кликните по нему дважды левой кнопкой мыши.
- Переместитесь на вкладку «Протоколы и порты».
- Теперь вы можете без проблем определить локальный порт.






Некоторые программы и службы могут использовать все предлагаемые порты, поэтому в этом меню вы не найдете конкретной привязки к протоколу. Тогда придется обращаться за помощью к одному из следующих методов.
Способ 3: Онлайн-сервисы
Онлайн-сервисы — очень популярный вариант определения открытых портов, поскольку многие пользователи не желают задействовать консоль, чтобы получить какую-либо информацию. На просторах интернета находится огромное количество подходящих сайтов, которые бесплатно выводят список прослушиваемых портов, а о трех самых популярных из них мы предлагаем прочесть далее.
Подробнее: Сканирование портов онлайн

Способ 4: TCPView
TCPView — небольшое программное обеспечение с графическим интерфейсом, которое было перекуплено компанией Microsoft и сейчас находится в свободном доступе на официальном сайте компании. По сути, это аналог рассмотренной выше команды, однако сведения показываются в более понятном виде, а наличие графического интерфейса является огромным плюсом TCPView.

- Перейдите по ссылке выше и скачайте TCPView с официального сайта.
- Устанавливать программу не нужно, поэтому ее сразу же можно запустить из полученного архива.
- В меню TCPView просмотрите список активных процессов, а затем обратите внимание на перечень локальных портов. Это поможет узнать, какие программы в Windows 10 используют порты, а значит, они являются открытыми.
- Переместитесь вправо по таблице, чтобы посмотреть, в каком состоянии находится порт. Например, он может прослушиваться, находиться в ожидании или вовсе не использоваться.




Способ 5: PortQry
PortQry — дополнительная консольная утилита от компании Microsoft, которая позволяет просмотреть открытые порты. Мы рекомендуем пользоваться ее в том случае, если команда netstat и другие варианты вам не подходят, но нужно путем ввода всего одной команды просмотреть список абсолютно всех открытых портов.
- Загрузка PortQry осуществляется с официального сайта компании Microsoft.
- По завершении загрузки остается только произвести инсталляцию, следуя отобразившимся на экране инструкциям. Не меняйте путь распаковки программы или при ознакомлении со следующими командами, описанными в инструкции, учитывайте новое расположение.
- Откройте «Командную строку» от имени администратора, например, через меню «Пуск».
- Перейдите там по пути установки PortQry, чтобы оказаться в ее корне. Осуществляется это путем ввода команды
cd + полный путь к директории. - Остается только ввести команду
portqry.exe –localи активировать ее нажатием на Enter для просмотра списка открытых локальных портов. - Опускайтесь вниз, ориентируясь по строкам и столбцам для определения статуса порта, его номера и внешнего адреса.






Способ 6: Веб-интерфейс маршрутизатора
Последний метод просмотра открытых портов в Windows 10 — переход к отдельному меню в интернет-центре роутера. Однако там можно увидеть только те порты, которые были вручную или по умолчанию открыты именно через настройки маршрутизатора, а осуществляется это на примере устройства от TP-Link так:
- Выполните авторизацию в веб-интерфейсе маршрутизатора, следуя инструкциям из следующей статьи.
Подробнее: Вход в веб-интерфейс роутеров
- В меню перейдите к разделу «Forwarding».
- Там вас интересует категория «Port Triggering».
- Ознакомьтесь со списком открытых портов, их адресами и статусом. По желанию любой из них можно закрыть, нажав всего по одной кнопке.



Если нужно открыть конкретный порт, который по каким-то причинам оказался закрыт, потребуется выполнить определенный алгоритм действий. Проще всего справиться с этой задачей, придерживаясь руководств по ссылкам далее.
Подробнее:
Открываем порты в брандмауэре Windows 10
Открываем порты на роутере
Еще статьи по данной теме:
Помогла ли Вам статья?
Is it possible in windows cmd line to check all of the network addresses (with ping or similar) to see which ones are taken/ have active devices:
for i = 0 to 255 ping 192.168.1.i //Print this
endThis is psuedo code obviously. I am wondering if it is possible to do something like this in windows cmd. It would be great if you didn’t need a batch file, but i understand if this is impossible.
PS. Also please mention if there is a program to do this, but it would be nice to do it in cmd.
asked Dec 4, 2012 at 22:44

Fantastic Mr FoxFantastic Mr Fox
26 gold badges94 silver badges171 bronze badges
FOR /L %i IN (1,1,254) DO ping -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txtChange 192.168.10 to match you own network.
By using -n 1 you are asking for only 1 packet to be sent to each computer instead of the usual 4 packets.
The above command will ping all IP Addresses on the 192.168.10.0 network and create a text document in the C:\ drive called ipaddresses.txt. This text document should only contain IP Addresses that replied to the ping request.
Although it will take quite a bit longer to complete, you can also resolve the IP Addresses to HOST names by simply adding -a to the ping command.
FOR /L %i IN (1,1,254) DO ping -a -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txtThis is from Here

6 gold badges25 silver badges98 bronze badges
answered Dec 4, 2012 at 22:50
I know this is a late response, but a neat way of doing this is to ping the broadcast address which populates your local arp cache.
This can then be shown by running arp -a which will list all the addresses in you local arp table.
ping 192.168.1.255
arp -aHopefully this is a nice neat option that people can use.
answered May 27, 2014 at 15:42
Best Utility in terms of speed is Nmap.
Nmap -sn -oG ip.txt 192.168.1.1-255
this will just ping all the ip addresses in the range given and store it in simple text file
It takes just 2 secs to scan 255 hosts using Nmap.

1 gold badge20 silver badges36 bronze badges
answered Sep 30, 2013 at 13:49
2 silver badges2 bronze badges
Provided the windows box is in the same subnet:
for /L %a in (1,1,254) do start ping 192.168.0.%aThis will complete in less than 15 seconds and
arp -a will return any alive host.
Fastest native way I know of in Windows.
5 gold badges32 silver badges40 bronze badges
answered Apr 21, 2017 at 15:21
1 silver badge2 bronze badges
This post asks the same question, but for linux – you may find it helpful. Send a ping to each IP on a subnet
nmap is probably the best tool to use, as it can help identify host OS as well as being faster. It is available for the windows platform on the nmap.org site
20 silver badges35 bronze badges
answered Dec 4, 2012 at 22:54

Paul Allen
1 silver badge9 bronze badges
An expansion and useful addition to egmackenzie’s “arp -a” solution for Windows –
Windows Example searching for my iPhone on the WiFi network
(pre: iPhone WiFi disabled)
- Open Command Prompt in Admin mode (R.C. Start & look in menu)
- arp -d <- clear the arp listing!
- ping 10.1.10.255 <- take your subnet, and ping ‘255’, everyone
- arp -a
- iPhone WiFi on
- ping 10.1.10.255
- arp -a
See below for example:

Here is a nice writeup on the use of ‘arp -d’ here if interested –
answered Mar 9, 2017 at 18:17

4 gold badges40 silver badges50 bronze badges
All you are wanting to do is to see if computers are connected to the network and to gather their IP addresses. You can utilize angryIP scanner: http://angryip.org/ to see what IP addresses are in use on a particular subnet or groups of subnets.
I have found this tool very helpful when trying to see what IPs are being used that are not located inside of my DHCP.
answered Dec 4, 2012 at 22:48
Benjamin Trent
3 gold badges33 silver badges41 bronze badges
Some things seem appeared to have changed in batch scripts on Windows 8, and the solution above by DGG now causes the Command Prompt to crash.
@echo off
set /a n=0
:repeat
set /a n+=1
echo 192.168.1.%n%
ping -n 1 -w 500 192.168.1.%n% | FIND /i "Reply">>ipaddresses.txt
if %n% lss 254 goto repeat
type ipaddresses.txtanswered Sep 11, 2013 at 19:05
Paul Lammertsma
15 gold badges134 silver badges187 bronze badges
aping can provide a list of hosts and whether each has responded to pings.
aping -show all 192.168.1.*answered Mar 26, 2020 at 7:55
@ECHO OFF
IF "%SUBNET%"=="" SET SUBNET=10
:ARGUMENTS
ECHO SUBNET=%SUBNET%
ECHO ARGUMENT %1
IF "%1"=="SUM" GOTO SUM
IF "%1"=="SLOW" GOTO SLOW
IF "%1"=="ARP" GOTO ARP
IF "%1"=="FAST" GOTO FAST
REM PRINT ARP TABLE BY DEFAULT
:DEFAULT
ARP -a
GOTO END
REM METHOD 1 ADDRESS AT A TIME
:SLOW
ECHO START SCAN
ECHO %0 > ipaddresses.txt
DATE /T >> ipaddresses.txt
TIME /T >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO ping -a -n 2 192.168.%SUBNET%.%%i | FIND /i "TTL=" >> ipaddresses.txt
GOTO END
REM METHOD 2 MULTITASKING ALL ADDRESS AT SAME TIME
:FAST
ECHO START FAST SCANNING 192.168.%SUBNET%.X
set /a n=0
:FASTLOOP
set /a n+=1
ECHO 192.168.%SUBNET%.%n%
START CMD.exe /c call ipaddress.bat 192.168.%SUBNET%.%n%
IF %n% lss 254 GOTO FASTLOOP
GOTO END
:SUM
ECHO START SUM
ECHO %0 > ipaddresses.txt
DATE /T >> ipaddresses.txt
TIME /T >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO TYPE ip192.168.%SUBNET%.%%i.txt | FIND /i "TTL=" >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO DEL ip192.168.%SUBNET%.%%i.txt
type ipaddresses.txt
GOTO END
:ARP
ARP -a >> ipaddresses.txt
type ipaddresses.txt
GOTO END
:END
ECHO DONE WITH IP SCANNING
ECHO OPTION "%0 SLOW" FOR SCANNING 1 AT A TIME
ECHO OPTION "%0 SUM" FOR COMBINE ALL TO FILE
ECHO OPTION "%0 ARP" FOR ADD ARP - IP LIST
ECHO PARAMETER "SET SUBNET=X" FOR SUBNET
ECHO.answered Nov 8, 2013 at 16:33
@echo off
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
arp -d
setlocal
setlocal enabledelayedexpansion
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr /i "192"`) do (
for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
for /f "tokens=1-4 delims=." %%c in ("%%b") do (
set _o1=%%c
set _o2=%%d
set _o3=%%e
set _o4=%%f
set _3octet=!_o1:~1!.!_o2!.!_o3!.
for /L %%a in (1,1,254) do start /min ping /n 1 /l 1 !_3octet!%%a
)))
endlocalAfter you run the batch file, type this command
arp -aAll devices connected to the network will be displayed
answered Oct 5, 2022 at 18:13

6 bronze badges
for /l %%a in (254, -1, 1) do ( for /l %%b in (1, 1, 254) do ( for %%c in (20, 168) do ( for %%e in (172, 192) do ( ping /n 1 %%e.%%c.%%b.%%a>>ping.txt ) ) )
)
pause>nul
27 gold badges90 silver badges100 bronze badges
answered Dec 2, 2014 at 17:29
- Используем команду netstat для просмотра открытых портов
- Вопросы и ответы

Netstat — одна из встроенных команд операционной системы Windows. В ее функциональность входит отображение состояния сети со всеми требуемыми деталями. Пользователь задействует встроенный синтаксис, чтобы отфильтровать результаты или задать дополнительные действия для этой утилиты. В рамках сегодняшнего материала мы бы хотели рассказать о доступных методах просмотра открытых портов с помощью этого стандартного инструмента.
Портами называют натуральные числа, которые записываются в заголовках протоколов передачи данных (TCP, UDP и так далее). Они определяют процесс получения и передачи информации в рамках одного хоста и в большинстве случаев используются онлайн-программами для установки соединения. Просмотр открытых портов может понадобиться в случае определения работоспособности приложений или при стандартном мониторинге сети. Лучше всего с этим справится команда netstat, а ее активация доступна с применением разных аргументов.
Отображение всех подключений и ожидающих портов
Самый простой аргумент, применяемый к утилите netstat, имеет обозначение -a, и отвечает за вывод сведений обо всех активных подключениях их портов, которые ожидают соединения. Такая информация доступна к просмотру без применения прав администратора и выводится на экран следующим образом:
- Поскольку рассматриваемая команда является консольной, потребуется запустить приложение, чтобы ее выполнить. Откройте меню «Пуск», найдите там «Командную строку» и запустите ее. О других методах перехода в консоль читайте в другом нашем материале по следующей ссылке.
- В поле ввода напечатайте
netstat -a, а затем нажмите на клавишу Enter. - На экране тут же начнет появляться список с доступными адресами.

Подробнее: Открытие командной строки в Windows 10


Мониторинг производится в режиме реального времени, поэтому не все результаты будут доступны к просмотру сразу. Придется подождать немного времени, чтобы все они могли прогрузиться. Во время этого не закрывайте консоль, если не хотите прервать процесс, ведь при повторном запуске команды все начнется заново.
Постраничное отображение открытых портов
К сожалению, приведенный выше вариант отображает не все необходимые данные об открытых портах, поскольку выводит он только те параметры, которые на текущий момент находятся в состоянии LISTENING. К тому же там не указывались уникальные идентификаторы процессов (PID), что тоже играет важную роль во время определенного мониторинга. Потому советуем обратить внимание немного на другие аргументы.
- В консоли пропишите
netstat -aon | moreи нажмите на Enter. - Здесь сразу же появится вся важная информация о портах, которые находятся в разных состояниях. В пятой колонке обозначаются идентификаторы.
- Не все порты выводятся сразу, поэтому нужно жать на Enter, чтобы каждый раз отображать еще по одной строке.
- Если вы увидите поле ввода, значит все страницы были успешно выведены на экран.




Теперь хотелось бы поговорить про используемые аргументы и значение увиденных параметров. Давайте сначала затронем знакомые буквы синтаксиса:

Важно также уточнить и состояние портов, поскольку они могут являться открытыми, но на этот момент не использоваться или ожидать своего подключения. В колонке «Состояние» могут отображаться такие показатели:
Эти объяснения должны разобраться помочь не только с составлением запросов для netstat, но и без проблем разобраться с полученной информацией.
Запись результатов в текстовый файл
Иногда требуется сохранить готовые результаты мониторинга в текстовый файл, чтобы выполнить дальнейшие действия, ведь копировать информацию прямо из консоли не всегда удобно, да и займет это намного больше времени, нежели просто указать дополнительный аргумент при вводе команды.
- Напишите, например,
netstat -aon | moreилиnetstat - a, а затем добавьте> netstat.txt, что означает запись результатов в указанный файл (он будет создан в пользовательской папке). После ввода нажмите на Enter. - Запустите файл, введя его название и формат в консоли.
- Теперь вы можете управлять содержимым и сохранить его в любом другом удобном месте.



Поиск по содержимому
В случае необходимости отображения только подключений с определенными параметрами или адресами лучше всего использовать дополнительную команду find, которая перед выводом сведений произведет фильтрацию данных, и это освободит вас от надобности вручную искать каждый соответствующий пункт. Тогда полная консольная команда приобретает следующий вид:
- Введите
netstat -a | find /I "LISTENING", что задаст параметр отображения только портов с состоянием LISTENING, аргумент /I при этом используется для отмены учета регистра символов. - В результатах отобразится только подходящая информация.


Выше вы узнали о методах определения открытых портов через встроенную команду netstat. После этого можете приступить к работе с программами или пробросу других портов в случае необходимости. К слову, этой теме посвящен отдельный материал на нашем сайте. Перейдите по указанным ниже ссылкам, чтобы ознакомиться с подробными инструкциями.
Команда netstat всегда показывает правильные результаты, однако если хотите убедиться в открытости порта другим путем, рекомендуем задействовать специальные онлайн-сервисы, позволяющие справиться с поставленной задачей.
Ping Port with PaPing Tool
The PaPing tool is a 3rd party tool created to ping remote specified port. The PaPing project is open source and located in Google Code.
> paping.exe wisetut.com -p 80 -c 5Ping Specific Port with Test-Connection In PowerShell
The Windows operating system provides the strong command-line interface named PowerShell with its recent versions. PowerShell provides a lot of useful commands like Test-NetConnection . The Test-NetConnection can be used to ping specified remote ports easily and provides detailed information. The Test-NetConnection is the preferred tool over the telnet command for Windows systems. The Test-NetConnection command is by default with PowerShell and Windows so there is no need for an extra installation process.
The syntax of the Test-NetConnection command is like below.
Test-NetConnection TARGET -p PORT- TARGET is an IP address or domain name to port ping.
- PORT is the remote system port number.
We will use the Test-NetConnection command to test google.com port number 80.
PS> Test-NetConnection google.com -p 80The output of the ping remote port with the Test-NetConnection command will be like below. We can see that remote system ComputerName, RemoteAddress, RemotePort, InterfaceAlias, SourceAddress, TcpTectSucceeded information is provided.
ComputerName : google.com RemoteAddress : 172.217.18.110 RemotePort : 80 InterfaceAlias : Ethernet0 SourceAddress : 192.168.142.130 TcpTestSucceeded : True

Let’s make another test for port number 89 for google.com.
PS> Test-NetConnection google.com -p 80The output is like below which means the ping port is failed. For failed ping port operations extra information like PingRelyDetails (RTT), TcpTestSucceeded is provided.
WARNING: TCP connect to (172.217.18.110 : 89) failed ComputerName : google.com RemoteAddress : 172.217.18.110 RemotePort : 89 InterfaceAlias : Ethernet0 SourceAddress : 192.168.142.130 PingSucceeded : True PingReplyDetails (RTT) : 46 ms TcpTestSucceeded : False

Ping Specific Port with nmap
The nmap is a security tool used to scan remote systems ports and services. The nmap can be also used to ping a specific port. Nmap can be installed for the Linux distributions like Ubuntu, Debian, Mint, Kali like below.
$ sudo apt install nmapFor Windows operating systems use the official nmap site Windows download section like below.
The syntax of the nmap command for the port ping is like below.
nmap -p PORT_RANGE TARGET- PORT_RANGE is the remote port number or protocol name. The PORT_RANGE can be also a range of port numbers too.
- TARGET is a domain name or IP address. Also the target can be an IP range too which includes multiple sequencial IP addresses.
Let’s make an example with the nmap to ping remote port. We will provide the port number with the -p parameter which will be 80 and the remote system is google.com.
$ nmap -p 80 google.comThe nmap is the fastest tool to ping a specified remote port. The command will be executed in 2 seconds and detailed output about the remote port will be provided like below. The line “80/tcp open http” simply expresses that the remote port number 80 responds to pings.
Starting Nmap 7.80 ( https://nmap.org ) at 2020-11-11 18:27 PST Nmap scan report for google.com (172.217.18.110) Host is up (0.036s latency). Other addresses for google.com (not scanned): 2a00:1450:4001:809::200e rDNS record for 172.217.18.110: zrh04s05-in-f110.1e100.net PORT STATE SERVICE 80/tcp open http Nmap done: 1 IP address (1 host up) scanned in 0.28 seconds

Alternatively, we can specify the IP address of the remote system we want to ping port.
$ nmap -p 80 172.217.18.110$ nmap -p 80-90 google.comThe output will be like below where the open ports will be listed with the STATE open.
Starting Nmap 7.80 ( https://nmap.org ) at 2020-11-11 18:32 PST Nmap scan report for google.com (172.217.18.110) Host is up (0.039s latency). Other addresses for google.com (not scanned): 2a00:1450:4001:809::200e rDNS record for 172.217.18.110: fra16s42-in-f14.1e100.net PORT STATE SERVICE 80/tcp open http 81/tcp filtered hosts2-ns 82/tcp filtered xfer 83/tcp filtered mit-ml-dev 84/tcp filtered ctf 85/tcp filtered mit-ml-dev 86/tcp filtered mfcobol 87/tcp filtered priv-term-l 88/tcp filtered kerberos-sec 89/tcp filtered su-mit-tg 90/tcp filtered dnsix

Ping Specific Port with nc (netcat) Command
The nc or with its well-known name netcat is a tool used by security professionals for remote connectivity and management. Similar to the telnet command nc command can be used to ping specific port numbers for a remote system.
The nc command is provided by the Linux distributions like Ubuntu, Debian, Mint, Kali and can be installed like below.
$ sudo apt install netcatFor Windows operating systems the nc command and executable can be downloaded from alternative locations where one of them is https://github.com/diegocr/netcat .
The syntax of the nc command is very similar to the telnet command. But the difference is -v and -z parameters should be specified. The -v parameter is used for verbose output in order to see the log or status information like connected or not connected. The -z parameter is used for scan mode which will check or scan the specified remote port.
nc -vz DOMAIN PORT
nc -vz IP PORT- The DOMAIN is the remote system domain name.
- The IP is the remote system IP address.
- The PORT is the remote system port number we want to ping.
$ nc -vz goole.com 80
Connection to goole.com 80 port [tcp/http] succeeded!We can see that the connection is succeeded which means the remote port number 80 responds to ping requests. We can also use the IP address for the remote system.
$ nc -vz 172.217.18.110 80$ nc -vz goole.com 89
nc: connect to goole.com port 89 (tcp) failed: Connection refusedAs we can see from the result we will get the “Connection refused” message which means the remote port does not respond to ping.
Ping Port with psping Command
Windows Sysinternals is used to debug, troubleshoot the Windows operating system. The psping is a Windows Sysinternals tool that can be used to ping a port. The syntax of the psping tool is like below.
psping HOST:PORT> psping 192.168.136.136:80Ping Specific Port with telnet Command
The most popular and basic tool to ping a remote port is the telnet command. Telnet is a tool and protocol created to connect remote systems via the command line. Telnet work from the command line and provides simple access to the remote telnet server. Telnet command uses the TCP protocol and first tries to connect remote port which is very useful to check remote port.
By default, telnet is not installed for both Linux and Windows systems. In Linux systems like Ubuntu, Debian, Mint, Kali you can install the telnet command like below.
$ sudo apt install telnetAlternatively, you can use 3rd party tools like Putty for telnet command but it is not practical as expected. Syntax of the telnet command to ping the remote port is like below. The telnet command only uses the TCP protocol which is the most popular transmission protocol. So only TCP ports can be pinged with the telnet command which can not be used for the UDP ports.
telnet IP PORT
telnet DOMAIN PORT- IP or DOMAIN is used to specify the remote system.
- PORT is the remote system port number which is a number from 9 to 65000.
Let’s ping the remote HTTP port with the telnet command by providing the port number as 80. We will ping the google.com TCP port number 80 like below.
$ telnet google.com 80The output will be like below where the telnet will try to connect remote system port number 80 and when the connection is established e will see the message “Connected to google.com.”
Trying 172.217.18.110...
Connected to google.com.
Escape character is '^]'.
get /
HTTP/1.0 400 Bad Request
Content-Type: text/html; charset=UTF-8
Referrer-Policy: no-referrer
Content-Length: 1555
Date: Thu, 12 Nov 2020 01:57:34 GMT
<!DOCTYPE html>
<html lang=en> <meta charset=utf-8>
...
Alternatively, we can try to ping a remote port with the IP address. We will just change the domain name with the IP address below.
$ telnet 172.217.18.110 80$ telnet google.com 89
Trying 172.217.18.110...
Trying 2a00:1450:4001:809::200e...
telnet: Unable to connect to remote host: Network is unreachable
Ping Port with curl Command
curl HOST:PORT$ curl 192.168.136.136:80If the remote port is open some response like a warning, error, etc is returned by the remote port service.



