С другой стороны, номера портов принадлежат протоколам транспортного уровня, таким как TCP и UDP. Номера портов помогают определить, куда пересылается Интернет или другое сетевое сообщение, когда оно приходит.
В этом руководстве вы узнаете, как проверить связь с портом в Windows и Linux с помощью различных инструментов.
Можно ли пропинговать конкретный порт?
Сетевые устройства используют протокол ICMP для отправки сообщений об ошибках и информации о том, успешна ли связь с IP-адресом. ICMP отличается от транспортных протоколов, поскольку ICMP не используется для обмена данными между системами.
Ping использует пакеты ICMP, а ICMP не использует номера портов, что означает, что порт не может быть опрошен. Однако мы можем использовать ping с аналогичным намерением — чтобы проверить, открыт порт или нет.
Некоторые сетевые инструменты и утилиты могут имитировать попытку установить соединение с определенным портом и ждать ответа от целевого хоста. Если есть ответ, целевой порт открыт. В противном случае целевой порт закрывается или хост не может принять соединение, потому что нет службы, настроенной для прослушивания подключений на этом порту.
Как пропинговать определенный порт в Linux?
Вы можете использовать три инструмента для проверки связи порта в Linux:
- Telnet
- Netcat (NC)
- Network Mapper (nmap)
Пинг определенного порта с помощью Telnet
Telnet — это протокол, используемый для интерактивной связи с целевым хостом через соединение виртуального терминала.
1. Чтобы проверить, установлен ли уже telnet
, откройте окно терминала и введите:
telnet
2. Если telnet
не установлен, установите его с помощью следующей команды
- Для CentOS/Fedora:
yum -y install telnet
- Для Ubuntu:
sudo apt install telnet
3. Чтобы пропинговать порт с помощью telnet
, введите в терминале следующую команду:
telnet [address] [port_number]
Где [address]
— это домен или IP-адрес хоста, а [port_number]
— это порт, который вы хотите проверить.
telnet google.com 443
Если порт открыт, telnet
устанавливает соединение. В противном случае он указывает на сбой.
4. Чтобы выйти из telnet
, нажмите Ctrl +]
и введите q
.
Пинг определенного порта с помощью Netcat
Netcat (nc) позволяет устанавливать соединения TCP и UDP, принимать оттуда данные и передавать их. Этот инструмент командной строки может выполнять множество сетевых операций.
1. Чтобы проверить, установлен ли netcat
:
- Для Debian, Ubuntu и Mint: введите
netcat -h
- Для Fedora, Red Hat Enterprise Linux и CentOS:
ncat -h
2. Если netcat не установлен, выполните в терминале следующую команду:
sudo apt install netcat
3. Чтобы пропинговать порт с помощью netcat
, введите следующее:
nc -vz [address] [port_number]
Выходные данные информируют пользователя об успешном подключении к указанному порту. В случае успеха — порт открыт.
Пинг определенного порта с помощью Nmap
Nmap — это сетевой инструмент, используемый для сканирования уязвимостей и обнаружения сети. Утилита также полезна для поиска открытых портов и обнаружения угроз безопасности.
1. Убедитесь, что у вас установлен Nmap, введя nmap -version
в терминал.
Если Nmap установлен, вывод информирует пользователя о версии приложения и платформе, на которой он работает.
2. Если в вашей системе нет Nmap, введите следующую команду:
- Для CentOS или RHEL Linux:
sudo yum install nmap
- Для Ubuntu или Debian Linux:
sudo apt install nmap
3. После установки Nmap в системе используйте следующую команду для проверки связи определенного порта:
nmap -p [port_number] [address]
Выходные данные информируют пользователя о состоянии порта и типе службы, задержке и времени, прошедшем до завершения задачи.
4. Чтобы проверить связь с более чем одним портом, введите nmap -p [number-range] [address]
.
Синтаксис [number-range]
— это диапазон номеров портов, которые вы хотите пропинговать, разделенные дефисом. Например:
nmap -p 88-93 google.com
Как пропинговать определенный порт в Windows?
Проверить связь с портом в Windows можно двумя способами:
- Telnet
- PowerShell
Пинг определенного порта с помощью Telnet
Перед использованием telnet убедитесь, что он активирован:
- Откройте панель управления.
- Щелкните «Программы», а затем «Программы и компоненты».
- Выберите «Включение или отключение компонентов Windows».
- Найдите клиент Telnet и установите флажок. Щелкните ОК.
Готово! Вы активировали клиент Telnet в системе.
После завершения активации можно пропинговать порт с помощью telnet. Для этого:
1. Введите cmd
в поиске в меню «Пуск». Щелкните на приложение Командная строка.
2. В окне командной строки введите
telnet [address] [port_number]
Где [address]
— это домен или IP-адрес хоста, а [port_number]
— это порт, который вы хотите проверить.
Выходные данные позволяют узнать, открыт ли порт и доступен ли он, иначе отображается сообщение об ошибке подключения.
Пинг определенного порта с помощью PowerShell
PowerShell — это текстовая оболочка, которая по умолчанию поставляется с Windows.
Чтобы проверить связь с портом с помощью PowerShell, выполните следующие действия:
1. Введите PowerShell
в поиске в меню «Пуск». Щелкните приложение Windows PowerShell.
2. В окне командной строке PowerShell введите:
Test-NetConnection [address] -p [port_number]
Если порт открыт и соединение прошло успешно, проверка TCP прошла успешно. В противном случае появится предупреждающее сообщение о том, что TCP-соединение не удалось.
Заключение
Теперь вы знаете, как выполнить эхо-запрос и проверить, открыт ли порт, с помощью нескольких сетевых инструментов и утилит в Linux и Windows.
Pinging a port is a useful way to test connectivity and ensure that a specific service on a target machine is accessible. While the traditional ping
command checks if a host is reachable, it doesn’t support ports directly. To check the status of a port, alternative methods like telnet
, PowerShell
, or third-party tools are required.
This guide explains how to “ping” a port on Windows using practical techniques.
Pinging a port can help:
1. Troubleshoot Network Issues: Ensure a specific service is running and reachable.
2. Test Firewalls: Verify that a firewall isn’t blocking a port.
3. Check Service Availability: Confirm that an application or server is accessible on a given port.
Method 1: Using Telnet
Step 1: Enable Telnet (If Not Already Installed)
- Press Win + S, type
Turn Windows features on or off
, and select it. - Scroll down and check Telnet Client.
- Click OK and wait for the installation to complete.
Step 2: Use Telnet to Ping a Port
-
Open Command Prompt:
– Press Win + S, typecmd
, and hit Enter. -
Type the following command:
bash
telnet <hostname> <port> -
Replace
<hostname>
with the target IP address or domain and<port>
with the desired port number.
Example:
bash
telnet 192.168.1.1 80
- If the connection is successful, the screen will go blank. If not, you’ll see an error message indicating the port is closed or unreachable.
Method 2: Using PowerShell
Step 1: Test the Port with PowerShell
-
Open PowerShell:
– Press Win + X and select Windows PowerShell or Terminal. -
Run the following command:
powershell
Test-NetConnection -ComputerName <hostname> -Port <port> -
Replace
<hostname>
with the target IP or domain and<port>
with the desired port number.
Example:
powershell
Test-NetConnection -ComputerName google.com -Port 443
- PowerShell will display the connectivity results, including whether the port is open or closed.
If you prefer a graphical interface or need additional features, third-party tools can help.
Recommended Tools:
-
Netcat (nc):
– Download and install Netcat on Windows.
– Use the following command in Command Prompt:
bash
nc -zv <hostname> <port> -
Nmap:
– Install Nmap from Nmap.org.
– Run the following command to scan the port:
bash
nmap -p <port> <hostname> -
Angry IP Scanner:
– A user-friendly tool for scanning IP addresses and ports.
– Download from Angry IP Scanner and follow the GUI instructions.
Comparison of Methods
Method | Ease of Use | Best For |
---|---|---|
Telnet | Moderate | Simple port checks on TCP |
PowerShell | Easy | Quick and detailed connectivity results |
Third-Party Tools | Easy | Advanced scanning and testing |
FAQs About Pinging Ports
Can I Ping a Port Directly with the Ping Command?
No, the ping
command in Windows does not support ports. It checks host reachability but not specific services or ports.
What Happens If a Port Is Closed?
If a port is closed, you won’t be able to establish a connection, and the tool will return an error or failure message.
How Do I Check UDP Ports?
Use tools like Nmap or specialized network scanners, as most methods above focus on TCP ports.
Pro Tips for Pinging Ports
- Check Firewalls: Ensure no firewalls are blocking the port on the target machine.
- Verify Service Status: Make sure the service associated with the port is running on the target host.
- Use Tools Wisely: PowerShell and Telnet are ideal for simple checks, while tools like Nmap provide more comprehensive scans.
Conclusion
Pinging a port on Windows is an essential skill for network troubleshooting and service testing. While the traditional ping
command doesn’t support ports, tools like Telnet, PowerShell, and third-party applications make it easy to check port availability.
Choose the method that best fits your needs, and ensure your network remains secure and functional. Happy troubleshooting!
В PowerShell для проверки доступности порта на удаленном компьютере можно использовать командлет Test-NetConnection. Этот командлет позволяет проверить доступность удаленного сервера или службы на нем, протестировать блокируется ли TCP порт файерволами, проверить доступность по ICMP и маршрутизацию. По сути, командлет Test-NetConnection позволяет заменить сразу несколько привычных сетевых утилит: ping, traceroute, telnet, сканер TCP портов и т.д.
Содержание:
- Проверка доступности TCP порта с помощью Test-NetConnection
- PowerShell: проверка открытых портов на нескольких IP хостах
- IP сканер сети на PowerShell
- Вывести список открытых портов в Windows
Проверка доступности TCP порта с помощью Test-NetConnection
Командлет Test-NetConnection можно использовать только для проверки TCP портов. Например, чтобы проверить, что на почтовом сервере открыт порт TCP 25 (SMTP протокол), выполните команду:
Test-NetConnection -ComputerName msk-msg01 -Port 25
Примечание. С помощью командлета Test-NetConnection можно проверить только TCP соединение, для проверки доступности UDP портов он не применим.
В сокращенном виде аналогичная команда выглядит так:
TNC msk-mail1 -Port 25
Разберем результат команды:
ComputerName : msk-msg01 RemoteAddress : 10.10.1.7 RemotePort : 25 InterfaceAlias : CORP SourceAddress : 10.10.1.70 PingSucceeded : True PingReplyDetails (RTT) : 0 ms TcpTestSucceeded : True
Как вы видите, командлет выполняет разрешение имени сервера в IP адрес, выполняется проверка ответа ICMP (аналог ping) и проверка ответа от TCP порта (доступность). Указанный сервер доступен по ICMP (
PingSucceeded = True
) и 25 TCP порт также отвечает (
RemotePort=25, TcpTestSucceeded= True
).
Примечание. Если команда вернула PingSucceeded=False и TcpTestSucceeded= True, скорее всего означает, что на удаленном сервере запрещен ICMP Ping.
Если выполнить команду Test-NetConnection без параметров, выполнится проверка наличия подключения к интернету на компьютере (проверяется доступность узла internetbeacon.msedge.net):
Для вывода детальной информации при проверки удаленного TCP порта можно добавить опцию -InformationLevel Detailed:
TNC 192.168.31.102 -Port 3389 -InformationLevel Detailed
Доступность популярных сервисов Windows на удаленном компьютере (HTTP, RDP, SMB, WINRM) можно проверить с помощью параметра CommonTCPPort.
Например, чтобы проверить доступность веб-сервера, можно использовать команду:
Test-NetConnection -ComputerName winitpro.ru -CommonTCPPort HTTP
Или проверить доступность стандартного RDP порта (TCP/3389):
Test-NetConnection msk-rds1 –CommonTCPPort RDP
Можно вывести все параметры, которые возвращает командлет Test-NetConnection:
Test-NetConnection msk-man01 -port 445|Format-List *
Если нужна только информация по доступности TCP порта, в более лаконичном виде проверка может быть выполнена так:
TNC msk-mail1 -Port 25 -InformationLevel Quiet
Командлет вернул True, значит удаленный порт доступен.
Совет. В предыдущих версиях Windows PowerShell (до версии 4.0) проверить доступность удаленного TCP порта можно было так:
(New-Object System.Net.Sockets.TcpClient).Connect('msk-msg01', 25)
Командлет Test-NetConnection можно использовать для трассировки маршрута до удаленного сервера при помощи параметра –TraceRoute (аналог команды трассировки маршрута tracert). С помощью параметра –Hops можно ограничить максимальное количество хопов при проверке.
Test-NetConnection msk-man01 –TraceRoute
Командлет вернул сетевую задержку при доступе к серверу в миллисекундах (
PingReplyDetails (RTT) : 41 ms
) и все IP адреса маршрутизаторов на пути до целевого сервера.
PowerShell: проверка открытых портов на нескольких IP хостах
С помощью PowerShell можно проверить доступность определенного порта на нескольких компьютерах. Сохраните список серверов или IP адресов в текстовый файл servers.txt.
Например, ваша задача – найти сервере на которых не отвечает или закрыт порт TCP/25:
Get-Content c:\Distr\servers.txt | where { -NOT (Test-Netconnection $_ -Port 25 -InformationLevel Quiet)}| Format-Table –AutoSize
Вы можете использовать PowerShell в качестве простейшую систему мониторинга, которая проверяет доступность серверов и выводит уведомление, если один из серверов недоступен.
Например, вы можете проверить доступность основных служб на всех контроллерах домена в AD (список DC можно получить командлетом Get-ADDomainController). Проверим следующие службы на DC (в утилите PortQry есть аналогичное правило Domain and trusts):
- RPC – TCP/135
- LDAP – TCP/389
- LDAP – TCP/3268
- DNS – TCP/53
- Kerberos – TCP/88
- SMB – TCP/445
$Ports = "135","389","636","3268","53","88","445","3269", "80", "443"
$AllDCs = Get-ADDomainController -Filter * | Select-Object Hostname,Ipv4address
ForEach($DC in $AllDCs){
Foreach ($P in $Ports){
$check=Test-NetConnection $DC.Ipv4address -Port $P -WarningAction SilentlyContinue
If ($check.tcpTestSucceeded -eq $true)
{Write-Host $DC.hostname $P -ForegroundColor Green -Separator " => "}
else
{Write-Host $DC.hostname $P -Separator " => " -ForegroundColor Red}
}
}
Скрипт проверит указанные TCP порты на контроллерах домена, и, если один из портов недоступен, выделит его красным цветом (можно запустить данный PowerShell скрипт как службу Windows).
IP сканер сети на PowerShell
Вы можете реализовать простой IP сканер, которые сканирует удаленные хосты или IP подсети на открытые/закрытые TCP порты.
Чтобы просканировать диапазон IP адресов с 10.10.10.5 до 10.10.10.30 и вывести компьютеры, на которых открыт порт 3389:
foreach ($ip in 5..30) {Test-NetConnection -Port 3389 -InformationLevel "Detailed" 10.10.10.$ip}
Можно просканировать диапазон TCP портов (от 1 до 1024) на указанном сервере:
foreach ($port in 1..1024) {If (($a=Test-NetConnection srvfs01 -Port $port -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){ "TCP port $port is open!"}}
Вывести список открытых портов в Windows
Если вам нужно вывести список портов, открытых на локальном компьютере, исопльзуется командлет Get-NetTCPConnection (это PowerShell-эквивалент NETSTAT). Полный список открытых портов на компьютере можно вывести так:
Get-NetTcpConnection -State Listen | Select-Object LocalAddress,LocalPort| Sort-Object -Property LocalPort | Format-Table
Если вам нужно проверить, какая программа (процесс) слушает определенный порт на вашем компьютере, выполните команду:
Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess | ft Id, ProcessName, UserName, Path
To check the connectivity to an IP address and a specific port in Windows Command Prompt, you can use the `telnet` command since the standard `ping` command does not support port scanning. Here’s how you can do it:
telnet <IP_ADDRESS> <PORT>
Replace `<IP_ADDRESS>` with the target IP address and `<PORT>` with the desired port number.
Understanding the Ping Command
What is the Ping Command?
The `ping` command is a fundamental network utility available in Windows CMD and most other operating systems. It’s primarily used to send packets to a specific IP address and receive responses. This helps determine whether a host is reachable in the network.
Under the hood, `ping` utilizes ICMP (Internet Control Message Protocol) to communicate. It sends echo request messages and listens for echo replies. This basic operation makes `ping` a valuable tool for diagnosing connectivity issues.
Why Ping a Port?
While `ping` is excellent for checking if an IP address is reachable, it has a significant limitation — it does not have the capability to check the status of specific ports directly. Ping is concerned with network availability, not the accessibility of services that run on particular ports.
Testing connectivity to a specific port is crucial for several reasons:
- Web Services: Ensure web servers are accepting traffic on ports like 80 (HTTP) or 443 (HTTPS).
- Game Connections: Validate that game servers are operational on designated ports.
- Security Services: Check firewall configurations and ensure necessary services are accessible.
Repair Windows Cmd: Quick Fixes and Tips
Methods to Ping IP with Port in CMD
Using Telnet to Test Ports
Telnet is a command-line tool that can help to check ports by attempting to establish a connection to the desired IP and port combination. Although often disabled by default in Windows, you can enable Telnet through Control Panel or install it via Windows Features.
To use Telnet, open your command prompt and type the following command:
telnet [IP Address] [Port Number]
Example: To test connectivity to a web server on port 80:
telnet example.com 80
If Telnet connects successfully, you’ll see a blank screen or the server’s response. If it fails, you might see a message indicating that the connection could not be established, such as «Could not open connection to the host.»
Using PowerShell as an Alternative
In scenarios where Telnet is not available or preferred, PowerShell provides a powerful alternative called `Test-NetConnection`. This command allows you to test both IP addresses and specific ports easily.
You can execute the following command in PowerShell:
Test-NetConnection -ComputerName [IP Address] -Port [Port Number]
Example: Testing a game server on port 25565 could look like this:
Test-NetConnection -ComputerName game.server.com -Port 25565
The output will provide valuable information, not just on the connectivity but also detailing whether the service on that port is responding, alongside the round-trip time.
Using Third-Party Tools
Though CMD and PowerShell provide effective solutions, there are numerous third-party tools like `Nmap` or online port-checking services that enhance functionality. `Nmap`, for example, is a robust tool for network scanning that lets you inspect multiple ports at once.
List in Windows Cmd: Quick and Easy Commands Explained
Important Notes on Pinging with Ports
Limitations of Ping in CMD
It is essential to understand that pinging does not include tests for specific ports. Ping commands only confirm the reachability of an IP address. As a result, it cannot diagnose service availability or blocked ports directly. Hence, if you need to test port connectivity, rely on Telnet or PowerShell, as discussed earlier.
Firewall Considerations
Network firewalls often block ICMP packets, which are the backbone of the `ping` command. This means a successful ping might not imply accessibility on specific ports.
When checking ports on your server, ensure that:
- The ports are open in the firewall settings.
- The associated services are currently active.
If you’re experiencing connectivity issues, investigating the firewall configuration should be your first step.
Mastering SCP in Windows Cmd: Quick Transfer Guide
Practical Examples of Pinging a Port in CMD
Example Scenario: Checking Web Server Port
Let’s say you want to ensure that a web server is accepting connections. You can use Telnet to check traffic on port 80:
telnet example.com 80
If you receive a blank screen, it typically means the connection is successful, and the server is online and accepting requests on that port.
Example Scenario: Testing Game Server Connectivity
If you’re an avid gamer, you might want to check if your game server is reachable. Here’s how you could do so with PowerShell:
Test-NetConnection -ComputerName game.server.com -Port 25565
The output will inform you if the connection was successful and if TCP traffic can reach your gaming server.
Rename File Windows Cmd: A Quick and Easy Guide
Conclusion
Pinging an IP with a port in Windows CMD requires understanding the limitations of `ping` and knowing alternative tools like Telnet and PowerShell. Utilizing these methods effectively allows you to troubleshoot network issues, ensuring that your applications and services are operational. Practice with the commands and scenarios provided to enhance your network troubleshooting skills.
Mastering Pwd in Windows Cmd: Your Quick Reference Guide
Further Reading and Resources
To further your understanding of CMD commands and network troubleshooting, consider exploring additional tutorials and resources available online. Engaging in community forums can also provide valuable insights and tips from fellow CMD users.
There were times when we used to test network connectivity of a specific port of the router using telnet command. Telnet used to come pre-installed in Windows but not in Windows 10. We explore different possibilities to check if a remote network port is open using command line options in Windows 10.
Windows 10 does not come with Telnet pre-installed. Even DOS Command Prompt has also become secondary with PowerShell taking the center stage.
Portqry used to be the command of choice for checking remote ports being alive and listening but it was only available up till Windows XP and Windows Server 2003.
Install Telnet in Windows 10
If you are going strictly with a DOS based command then you are left with no option but to install telnet in Windows 10. To install Telnet, follow the instructions below:
- Open Command Prompt Run –> cmd
- Run the following command:
pkgmgr /iu:”TelnetClient” - Go to Run –> telnet
Check whether the port is open or not using Command Prompt
To check the network port, follow the instructions below:
Open Telnet using the three steps described above and issue the following command:
open google.com 80
Where google.com is the host you want to test. You can also put an IP address instead of the name. 80 is the port number which you want to probe. You should replace 80 with you desired port number.
If you receive “Press any key to continue” prompt, this means that the port is open and responding to telnet. If you receive “Could not open connection” or a blank screen with blinking cursor, this means the port is closed.
If you receive “Connection to host lost“, this means that the port is open but the host is not accepting new connections.
Check open port using PowerShell
Since Microsoft is pushing PowerShell and CMD has become a legacy system, we should be using PowerShell for most of our working. Let’s check whether a remote network port is open and listening or not.
- Open PowerShell by going to Run –> powershell
- Run the following command
tnc google.com -port 80
tns is short for Test-NetworkConnection command. google.com is the host name. You can also put an IP address instead of the host name. You can specify the port number using the -port switch at the end of tnc command.
The TNC command will give you basic information about the network connection like computer name, IP address, Interface through which you are connecting, source IP, whether the ping is successful or not, Ping reply time and finally TcpTestSucceeded. TcpTestSucceeded will give you True if the port is open and false if the port is closed.
These commands and techniques are very useful when you are troubleshooting a network. Please let us know if this has been useful for you in the comments below and we will add more troubleshooting techniques in future.