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:
If you are working on a Linux Server or Desktop, you can use the below command to install Telnet on that machine:
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:
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:
$ telnet 172.67.161.26 80 Trying 172.67.161.26. Connected to 172.67.161.26. Escape character is '^]'. $ telnet 172.67.161.26 443 Trying 172.67.161.26. Connected to 172.67.161.26. Escape character is '^]'.
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.
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.
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.
To install Nmap on your Linux machine, you can use the below command:
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.
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.
C:\Users\christian>nmap -p 443 172.67.161.26 Starting Nmap 7.92 ( https://nmap.org ) at 2022-02-10 06:50 Romance Standard Time Nmap scan report for 172.67.161.26 Host is up (0.028s latency).
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.
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.
PS C:\Users\christian> Test-NetConnection -p
Below is an example of what this would look like on a local network:
Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\christian> Test-NetConnection 192.168.1.1 -p 80 ComputerName : 192.168.1.1 RemoteAddress : 192.168.1.1 RemotePort : 80 InterfaceAlias : Wi-Fi SourceAddress : 192.168.1.68 TcpTestSucceeded : True
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.
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!
My name is Christian. I am a 27-year-old pragmatic software engineer with a passion for .NET, Cloud, and Containers. In my spare time, I share my knowledge and love teaching other people about tech.
Обновлено: 19.10.2021 Опубликовано: 27.06.2016
Мы рассмотрим использование команды ping для Windows и, немного, для Linux.
В зависимости от используемой операционной системы опции команды будут иметь разные назначения. Поэтому, если мы хотим понять все возможности, стоит ознакомиться с опцией help.
Независимо от системы, команду ping можно применять так:
Для просмотра в 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 | Использует заголовок маршрута для проверки и обратного маршрута. |
При минимальной инсталляциии данной системы или использовании docker, утилиты ping может не быть. В таком случае мы увидим ошибку:
bash: ping: command not found
Для ее установки можно воспользоваться менеджером установки пакетов. В зависимости от типа операционной системы, наши команды будут немного отличаться.
а) для систем на базе deb (Debian, Ubuntu, Mint):
б) для систем на базе RPM (Rocky Linux, CentOS, Red Hat, Fedora):
Готово, теперь можно пользоваться командой 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 означает, что удаленный узел недоступен. Администратор ресурса может намеренно отключить ответы на эхо-запросы.
Также важно знать, что ping не использует конкретный номер порта. Чтобы открыть возможность пинга, необходимо либо найти соответствующую опцию (во многих домашних роутерах) или разрешить ICMP (Internet Control Message Protocol) на брандмауэре. Ну, или наоборот — чтобы закрыть возможность пинга, блокируем запросы ICMP.
С помощью команды ping нельзя проверить открытость того или иного порта.
Для этих целей используется команда telnet или программа, например, nmap.
Adblock