Борьба за миллисекунды. Как выбрать сервер с наименьшим пингом
Время на прочтение5 мин
Количество просмотров49K
Для многих задач задержки между клиентом и сервером критически важны, например в онлайн играх, видео/голосовых конференциях, IP телефонии, VPN и т.д. Если сервер будет слишком удален от клиента на уровне IP-сети, то задержки (в народе «пинг», «лаг») будут мешать работе.
Географическая близость сервера не всегда равна близости на уровне IP маршрутизации. Так, например, сервер в другой стране может быть «ближе» к вам, чем сервер в вашем городе. Все из-за особенностей маршрутизации и построения сетей.
Как выбрать сервер максимально близкий ко всем потенциальным клиентам? Что такое связность IP-сетей? Как направить клиента на ближайший сервер? Разберемся в статье.
Измеряем задержки
Для начала научимся измерять задержки. Эта задача не так проста, как может показаться, потому что для разных протоколов и размеров пакета задержки могут отличаться. Также можно не заметить кратковременные явления, например провалы продолжительностью в несколько миллисекунд.
ICMP — обычный ping
Будем использовать юниксовую утилиту ping, она позволяет вручную установить интервалы между посылками пакетов, чего не умеет версия ping для windows. Это важно, потому что, если паузы между пакетами долгие, можно просто не увидеть, что происходит между ними.
Размер пакета (опция -s) — по умолчанию утилита ping посылает пакеты размером 64 байта. С такими маленькими пакетами могут быть не заметны явления, проявляющиеся с большими пакетами, поэтому мы будет устанавливать размер пакета 1300 байт.
Интервал между пакетами (опция -i) — время между посылками данных. По умолчанию пакеты посылаются раз в секунду, это очень долго, реальные программы шлют сотни и тысячи пакетов в секунду, поэтому установим интервал 0.1 секунду. Меньше просто не разрешает программа.
В итоге команда выглядит так:
ping -s 1300 -i 0.1 yandex.ru
Такая конструкция позволяет увидеть более реалистичную картину задержек.
Пинг по UDP и TCP
В некоторых случаях, TCP-подключения обрабатываются не так, как ICMP пакеты, и из-за этого замеры могут отличаться в зависимости от протокола. Также часто бывает, что хост просто не отвечает на ICMP, и обычный пинг не работает. Так, например, всю жизнь делает хост microsoft.com.
Утилита nping от разработчиков знаменитого сканера nmap умеет генерировать любые пакеты. Ее можно использовать в том числе для измерения задержек.
Так как UDP и TCP работают на определенных, нам нужно «пинговать» конкретный порт. Попробуем пропинговать TCP 80, то есть порт веб-сервера:
$ sudo nping --tcp -p 80 --delay 0.1 -c 0 microsoft.com
Starting Nping 0.7.80 ( https://nmap.org/nping ) at 2020-04-30 13:07 MSK
SENT (0.0078s) TCP 10.0.0.1:63236 > 13.77.161.179:80 S ttl=64 id=49156 iplen=40 seq=3401731188 win=1480
SENT (0.1099s) TCP 10.0.0.1:63236 > 13.77.161.179:80 S ttl=64 id=49156 iplen=40 seq=3401731188 win=1480
RCVD (0.2068s) TCP 13.77.161.179:80 > 10.0.0.1:63236 SA ttl=43 id=0 iplen=44 seq=1480267007 win=64240 <mss 1440>
SENT (0.2107s) TCP 10.0.0.1:63236 > 13.77.161.179:80 S ttl=64 id=49156 iplen=40 seq=3401731188 win=1480
RCVD (0.3046s) TCP 13.77.161.179:80 > 10.0.0.1:63236 SA ttl=43 id=0 iplen=44 seq=1480267007 win=64240 <mss 1440>
SENT (0.3122s) TCP 10.0.0.1:63236 > 13.77.161.179:80 S ttl=64 id=49156 iplen=40 seq=3401731188 win=1480
RCVD (0.4247s) TCP 13.77.161.179:80 > 10.0.0.1:63236 SA ttl=42 id=0 iplen=44 seq=2876862274 win=64240 <mss 1398>
Max rtt: 112.572ms | Min rtt: 93.866ms | Avg rtt: 101.093ms
Raw packets sent: 4 (160B) | Rcvd: 3 (132B) | Lost: 1 (25.00%)
Nping done: 1 IP address pinged in 0.43 seconds
По умолчанию nping посылает 4 пакета и останавливается. Опция -c 0 включает бесконечную посылку пакетов, чтобы остановить программу, нужно нажать Ctrl+C. В конце будет показана статистика. Видим, что среднее значение rtt (round-trip time) равно 101мс.
MTR — traceroute на стероидах
Программа MTR (англ. My Traceroute) — продвинутая утилита для трассировки маршрутов до удаленного хоста. В отличии от обычной системной утилиты traceroute (в windows это утилита tracert), умеет показывать задержки до каждого хоста в цепочке следования пакета. Также умеет трассировать маршруты не только по ICMP, но и по UDP и TCP.
$ sudo mtr microsoft.com
(Кликабельно) Интерфейс программы MTR. Запущенна трассировка маршрута до microsoft.com
MTR сразу показывает пинг до каждого хоста в цепочке, притом данные постоянно обновляются, пока программа запущена и можно видеть кратковременные изменения.
На скриншоте видно, что на узле №6 есть потери пакетов, но на самом деле это не совсем так, потому как некоторые маршрутизаторы могут просто отбрасывать пакеты с истекшим TTL и не возвращать ответ с ошибкой, поэтому данные о потерях пакетов тут можно игнорировать.
WiFi против кабеля
Эта тема не совсем относится к статье, но на мой взгляд очень важна в контексте задержек. Я очень люблю WiFi, но, если у меня есть хоть малейшая возможность подключиться кабелем к интернету, я ею воспользуюсь. Также я всегда отговариваю людей использовать WiFi камеры.
Если вы играете в серьезные онлайн-шутеры, вещаете потоковое видео, торгуете на бирже: пожалуйста, используйте интернет по кабелю.
Вот наглядный тест для сравнения WiFi и кабельного подключения. Это ping до WiFi роутера, то есть еще даже не интернет.
(Кликабельно) Сравнение ping до WiFi роутера по кабелю и по WiFi
Видно, что по WiFi задержки больше на 1мс и иногда бывают пакеты с задержками в десять раз больше! И это только короткий отрезок времени. При этом тот же самый роутер выдает стабильные задержки <1мс.
В примере выше используется WiFi 802.11n на 2.4GHz, к точке доступа по WiFi подключен только ноутбук и телефон. Если бы на точке доступа было больше клиентов, результаты были бы сильно хуже. Именно поэтому я так против перевода всех офисных компьютеров на WiFi, если есть возможность дотянуться до них кабелем.
IP связность
Итак, мы научились измерять задержки до сервера, попробуем найти ближайший сервер к нам. Для этого можем посмотреть, как устроена маршрутизация у нашего провайдера. Для этого удобно использовать сервис bgp.he.net
При заходе на сайт видим, что наш IP-адрес принадлежит автономной системе AS42610.
Посмотрев на граф связности автономным систем, можем увидеть через каких вышестоящих провайдеров наш провайдер связан с остальным миром. Каждая из точек кликабельна, можно зайти и почитать, что это за провайдер.
Граф связности автономных систем провайдера
Используя этот инструмент можно изучить, как устроены каналы любого провайдера, в том числе и хостинга. Посмотреть к каким провайдерам он подключен напрямую. Для этого нужно вбить в поиск bgp.he.net IP-адрес сервера и посмотреть на граф его автономной системы. Также можно понять, как один датацентр или хостинг-провайдер связан с другим.
Большинство точек обмена трафиком предоставляют специальный инструмент, называемый, looking glass, позволяющий выполнить ping и traceroute со стороны конкретного роутера на точке обмена.
Вот, например, looking glass от МГТС
Так, выбирая сервер, мы можем заранее посмотреть как он будет выглядеть с разных точек обмена трафиком. И если наши потенциальные клиенты находятся в определенной географической зоне, мы можем найти оптимальную локацию для сервера.
Выбираем ближайший сервер
Мы решили упростить процедуру поиска оптимального сервера для наших клиентов и сделали страницу с автоматическим тестом ближайших локаций: дата-центры RUVDS.
При заходе на страницу скрипт измеряет задержки от вашего браузера до каждого сервера и отображает их на интерактивной карте. При клике на датацентр показывается информация с результатами тестов.
Кнопка ведет на страницу теста задержек до всех наших датацентров. Чтобы посмотреть результаты тестирования нажмите на точку датацентра на карте
Команда ping
— это сетевой инструмент для проверки работоспособности удаленной системы. Другими словами, команда определяет, доступен ли определенный IP-адрес или хост. Ping использует протокол сетевого уровня, называемый Internet Control Message Protocol (ICMP), и доступен во всех операционных системах.
С другой стороны, номера портов принадлежат протоколам транспортного уровня, таким как 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.
Posted by
on March 11, 2015
Most of us would be familiar with the simple ICMP based ‘ping’ command which allows us to test for a basic response from some network connected device. While great for basic troubleshooting it does not allow us to confirm if the particular host at the other end is responding on TCP or UDP ports where the majority of services are likely to be provided.
Ping isn’t the be all and end all of network troubleshooting, if a firewall blocks inbound ICMP traffic then a ping will not succeed which can produce a false perception that the host is down as it is not responding to the ping, however other services could still be responding fine.
Alternatively while ping may come back fine with a response it doesn’t indicate if a web server is responding on port 80 for HTTP requests, the web server may have failed and no longer be responding.
So if ping is ICMP based, can we hit a TCP or UDP port for response instead? The answer is yes, let’s take a look.
Enter tcping
tcping is one such tool that can be used to check that a TCP port is responding, there are a few versions available however I use this one: http://www.elifulkerson.com/projects/tcping.php
The manual is on the same page, basically you can run a command similar to the below.
C:\Users\Admin\Desktop>tcping.exe google.com 443 Probing 150.101.161.230:443/tcp - Port is open - time=2.203ms Probing 150.101.161.230:443/tcp - Port is open - time=1.426ms Probing 150.101.161.230:443/tcp - Port is open - time=1.764ms Probing 150.101.161.230:443/tcp - Port is open - time=1.393ms Ping statistics for 150.101.161.230:443 4 probes sent. 4 successful, 0 failed. Approximate trip times in milli-seconds: Minimum = 1.393ms, Maximum = 2.203ms, Average = 1.697ms
Here we are using tcping to check port 443 at google.com. As can be seen the port is showing as being open and responding, if the port is not open it will show as no response after 2000ms by default.
You could also use telnet to test for TCP connectivity to a port, however the tcping tool provides further features as outlined in the usage section here. Some such features include being able to continually run the test allowing a way to generate traffic for you to watch out for in live packet captures as well as the response time.
What about UDP?
As UDP is a connectionless protocol, determining if it is responding is a bit different. A TCP ‘ping’ works by performing a three way hand shake, the source will send a SYN to the destination, the destination will reply with a SYN-ACK, and the source will then send an ACK completing the handshake and establishing the connection. As UDP does not establish a connection we can’t just look for this to determine if the port is responding, we instead need to send specific data and see if we receive a response.
NMAP is a great tool for this, you can download it and use it to port scan a destination address to determine what ports are open.
In this example we are querying if 8.8.8.8 is responding on UDP port 53, as it serves DNS we would expect it to be open.
C:\Users\Admin\Desktop\nmap-6.47>nmap -sU -p 53 8.8.8.8 Nmap scan report for google-public-dns-a.google.com (8.8.8.8) Host is up (0.0050s latency). PORT STATE SERVICE 53/udp open|filtered domain Nmap done: 1 IP address (1 host up) scanned in 5.31 seconds
The open|filtered result is used when nmap is unable to determine if the port is open or filtered, the open port may not have given a response. It shows that the service has been identified as ‘domain’ as it’s for serving DNS. I’ve tested this to some other DNS servers out on the Internet and some do show as open only confirming that they are responding.
NMAP can also be used to check a TCP port is open in a similar way, just change -sU to -sT.
Why a port may not respond
There are a few simple reasons that a port may not respond to your test.
- A firewall is blocking the traffic: There may be a firewall running between the source and destination filtering the traffic depending on the rules in place even if you know the destination should be responding on a particular port.
- The destination may not be listening on the port: Simply put, the destination you are trying to connect to may not have any services listening on the port specified so there will not be any response. This can also happen if a service has been stopped, for example if you stop Apache a web server will no longer respond to port 80 requests.
- There is some other network problem between the source and destination of the traffic: There could be any number of network connectivity problems between the source and destination, if possible check the network however if the traffic is traversing the Internet you will be limited in what you can check.
You can check the connectivity along the path of the traffic by running a packet capture with something like Wireshark or tcpdump, this will show you where the traffic is getting through to and where it’s being stopped along the route. You could run it on the source and destination servers, as well as devices in between that you have access to such as firewalls or routers. Follow the flow of traffic until you determine where the problem is.
Summary
While performing a TCP ‘ping’ to a destination you can confirm if it is responding as intended, though there are a few reasons the port may not respond as noted. UDP can be checked however it’s a bit more difficult to be certain if you’re correctly receiving a response so the tests aren’t always reliable, which makes sense as UDP is not a reliable protocol. These tests can be useful when testing security by confirming if ports are open or closed.
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!
The ping command is one of the base commands while working with computer networks.
This simple command is mainly used in its simplest form, without added options, just with a hostname or an IP address. This is normally the easiest way to check if two devices are reachable in a network. But what if we want to ping an address on a specific port?
The first thing a Mac or Linux user would do is consult the man page for the ping command. From there you’d expect to find some documentation and eventually the right syntax to specify a custom port.
You’ll be disappointed, as there’s no indication on the ping man page about that.
As we’ll see, there’s no way to ping a specific port. There’s also a reason for this, keep reading to discover it and see some simple alternatives you have.
How does the ping command work
The ping command uses the ICMP protocol, and its purpose is generally to test the connectivity between two network devices.
When we launch the ping command from a device to a remote host, an ICMP packet is sent through the network to the destination. If there’s network connectivity between the two, and the destination host is not explicitly blocking the ICMP protocol, the destination will send back an ICMP echo reply to confirm.
The source device will know if there’s connectivity based on receiving or not the ICMP echo reply.
For example, we can check the connectivity with the google server by launching the following command in a terminal window:
ping google.com
Why you can’t specify a port on the ping command
The ping tool uses the standard ICMP echo protocol, and its purpose is to check the connectivity between two hosts. ICMP is a Layer3 (network) protocol, while ports belong to transport layer protocols (layer 4), so there’s no concept of them in it.
When we want to ping a specific port we usually want to test if a specific service is reachable on the target host, and this is a different thing from checking connectivity on the network level.
We said that the ping command doesn’t allow us to specify a port, and that usually when we need to do it, we need to check if a service is active on the destination host. So what should we do now?
Let’s see some alternatives we can use to perform this apparently simple task.
Using telnet to test a specific port
The most common alternative, probably because it’s included by default in most operating systems, is the telnet command.
The telnet client is included in the windows command prompt, in most Linux distributions, and can be easily installed in macOS.
With telnet, you can easily open a connection to an IP address or a hostname, and you can specify the remote port to connect to.
The syntax for a simple connection with telnet is the following one:
telnet <destination ip/hostname> <port number>
For example, in my network, I have a router with IP address 10.24.1.1. I can check that the web configuration interface is reachable on the destination port 80 with the following:
telnet 10.24.1.1 80
The “Connected to 10.24.1.1.
” message will confirm that I’ve been able to successfully connect to the router.
To close the connection you have to use the key combination <Ctrl> + ]. Once you pressed the escape combination, you can press q and then the enter key to close the connection.
If you have a Linux system like Ubuntu and you get a “command not found
” error, you can install the telnet utility with:
sudo apt-get install telnet
If you’re on windows and get a command not found error, then you probably have to activate it by going to the control panel, then into “Programs and Features”, “Turn Windows features on or off”, select “telnet Client” and click on OK to confirm. It could also be necessary to restart the command prompt to enable the new tool.
Testing a port with nc (netcat)
Another useful tool you can use to determine if you can connect to a remote port is nc (netcat).
This tool is available on Unix systems like Linux and mac OS.
To make the test, we will use the -v
option for verbose output, and the -z
for scanning mode.
For example, we can test if we can reach the google’s server on the default port 80:
nc -vz googlecom 80
The tool will test the remote server at the target port, and we’ll have an output like the following one.
Unlike the telnet command, netcat tests only if you can open a connection. If the remote system port number is unreachable we will get a “Connection refused
” error.
If you get a “command not found
” error on Linux, you can install Netcat from the repositories:
sudo apt-get install netcat
Check a port using nmap
Another way to test a remote system port number is by using the nmap command.
Nmap allows us to scan a range of numbers, and eventually do it on more than a single remote host. This is why Nmap can be seen as a malicious port scan tool.
The official nmap documentation on their website starts with a long disclaimer about the use of a port scanner and its legal implication. You can find it on Nmap.org website here. I recommend using this tool on a target remote server you have control of, and assume that you read the article about potential legal issues before using it.
Nmap uses the -p option to specify a target port, a list, or a port range. You can for example make a list of common ports used for various services.
Nmap is more advanced than the simple telnet command, as you can scan different protocols and different remote systems ports for each protocol.
This last feature is achieved by combining the protocol with port numbers in the -p option. You can use for example T: for TCP and U: For UDP to scan tcp port 80 and UDP port 8765 by combining them in -p T:80,U:8765
.
For more details about the scanning functions of Nmap you can read the -p option reference page.
To scan a single service on a single host you can use the following syntax:
nmap -p <port number> <ip or domain>
As always, if Nmap is not installed in your Linux system and you get the command not found error message, you can install it with apt:
sudo apt-get install nmap
Testing a remote system port number in Windows with Windows PowerShell
If you need to test a port in Windows, many of the preceding solutions are not available on your operating system.
There’s, however, a tool you can use on your PowerShell. It’s called Test-NetConnection, and it allows to specify the remote system port number with the -p option.
The basic syntax to use the Test-NetConnection tool is simple:
Test-NetConnection <IP address> -p <port number>
We can try to test google’s host at port 80 again by executing the following command in a PowerShell window:
Test-NetConnection google.com -p 80
The output will be similar to the following one:
The last row TcpTestSucceded : True
will confirm that our test went well.
Conclusions
As we saw, there are valid alternatives to echo ping messages to verify if a service is reachable on a remote host.
There are for sure other alternatives, like using a 3rd party tool or in some situations using the curl command, but these are the most common ways to ping a specific port on Linux, Windows, and macOS.