Linux ping specific port

How to ping a specific port

I often use the ping command to check if a website is available or not, or if I can access a machine, so basically mostly for diagnostics, and what would be really useful is if I could specify which port(s) those ICMP echoes go to, is there any way of doing this with ping , or another tool which would allow for me to easily do this without having to generate packets manually? An option for instance would be to create a custom ICMP packet set to go to a specific port, and then I could use bittwist to send it, and Wireshark to monitor if I am getting anything in return, but this seems a bit of a hassle to do every time, so I was wondering if there is an easier route?

2 Answers 2

IIRC you cannot send a «ping» packet to a specific port.

On a port, there is a «software» listening. This software will implement it’s own protocol — HTTP, SMTP, FTP, or even some own protocol.

Those servers won’t respond to an ICMP packet. ICMP packets need to be sent to the ICMP port.

However, you may just try to open a TCP connection ( telnet host 12345 ) and see if the connection is successfully.

Here is an example of how to ping a specific IP-port on your network:

  1. Download and install nMap.
  2. Run ifconfig -a to identify your network topology; the terminal output should display the host IP-address traced to your command-line, displayed after «inet» (e.g. inet: 10.0.0.2 ).
  3. Now open the nMap tool to scan your network by running nmap -sP network-ip-address topology/24 (e.g. nmap -sP 10.0.0.1/24 ); that should display all hosts connected to the network.
  4. Locate the host IP-address of the port you wish to ping; for example, if your network is hosting a VPN server on a router at IP address 10.0.0.233 . First, try to ping the address by running nmap -sn host-ip-address (eg nmap -sn 10.0.0.233 )- the terminal output should return a report that the server is either up or down.
  5. However, sometimes a host may only be visible or identifiable if you ping a specific port by running nmap -Pn port-number ip-address ; for example, the subject router may only be traceable if we ping a specific port on the router- in this case UDP port 1143 for OpenVPN (e.g. nmap -Pn 1143 10.0.0.233 ). The aforementioned command should confirm that the port is open within the terminal output, even if the host is ostensibly down according to the initial run of the nmap port-scan.

Hope that helps- it helped me!

Читайте также:  Отображение кириллицы в linux

You must log in to answer this question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

Ubuntu and the circle of friends logo are trade marks of Canonical Limited and are used under licence.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Как сделать пинг порта в Linux и Windows

img

Команда ping — это сетевой инструмент для проверки работоспособности удаленной системы. Другими словами, команда определяет, доступен ли определенный IP-адрес или хост. Ping использует протокол сетевого уровня, называемый Internet Control Message Protocol (ICMP), и доступен во всех операционных системах.

С другой стороны, номера портов принадлежат протоколам транспортного уровня, таким как TCP и UDP. Номера портов помогают определить, куда пересылается Интернет или другое сетевое сообщение, когда оно приходит.

В этом руководстве вы узнаете, как проверить связь с портом в Windows и Linux с помощью различных инструментов.

Можно ли пропинговать конкретный порт?

Сетевые устройства используют протокол ICMP для отправки сообщений об ошибках и информации о том, успешна ли связь с IP-адресом. ICMP отличается от транспортных протоколов, поскольку ICMP не используется для обмена данными между системами.

Ping использует пакеты ICMP, а ICMP не использует номера портов, что означает, что порт не может быть опрошен. Однако мы можем использовать ping с аналогичным намерением — чтобы проверить, открыт порт или нет.

Некоторые сетевые инструменты и утилиты могут имитировать попытку установить соединение с определенным портом и ждать ответа от целевого хоста. Если есть ответ, целевой порт открыт. В противном случае целевой порт закрывается или хост не может принять соединение, потому что нет службы, настроенной для прослушивания подключений на этом порту.

Как пропинговать определенный порт в Linux?

Вы можете использовать три инструмента для проверки связи порта в Linux:

Пинг определенного порта с помощью Telnet

Telnet — это протокол, используемый для интерактивной связи с целевым хостом через соединение виртуального терминала.

1. Чтобы проверить, установлен ли уже telnet , откройте окно терминала и введите:

telnet

2. Если telnet не установлен, установите его с помощью следующей команды

3. Чтобы пропинговать порт с помощью telnet , введите в терминале следующую команду:

telnet [address] [port_number]

Где [address] — это домен или IP-адрес хоста, а [port_number] — это порт, который вы хотите проверить.

telnet

Если порт открыт, 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 не установлен, выполните в терминале следующую команду:

3. Чтобы пропинговать порт с помощью netcat , введите следующее:

nc -vz [address] [port_number]

nc -vz

Выходные данные информируют пользователя об успешном подключении к указанному порту. В случае успеха — порт открыт.

Пинг определенного порта с помощью Nmap

Nmap — это сетевой инструмент, используемый для сканирования уязвимостей и обнаружения сети. Утилита также полезна для поиска открытых портов и обнаружения угроз безопасности.

Читайте также:  Python linux установка pip

1. Убедитесь, что у вас установлен Nmap, введя nmap -version в терминал.

nmap

Если Nmap установлен, вывод информирует пользователя о версии приложения и платформе, на которой он работает.

2. Если в вашей системе нет Nmap, введите следующую команду:

  • Для CentOS или RHEL Linux: sudo yum install nmap
  • Для Ubuntu или Debian Linux: sudo apt install nmap

3. После установки Nmap в системе используйте следующую команду для проверки связи определенного порта:

nmap -p [port_number] [address]

nmap -p

Выходные данные информируют пользователя о состоянии порта и типе службы, задержке и времени, прошедшем до завершения задачи.

4. Чтобы проверить связь с более чем одним портом, введите nmap -p [number-range] [address] .

Синтаксис [number-range] — это диапазон номеров портов, которые вы хотите пропинговать, разделенные дефисом. Например:

nmap range

Как пропинговать определенный порт в Windows?

Проверить связь с портом в Windows можно двумя способами:

Пинг определенного порта с помощью Telnet

Перед использованием telnet убедитесь, что он активирован:

  1. Откройте панель управления.
  2. Щелкните «Программы», а затем «Программы и компоненты».
  3. Выберите «Включение или отключение компонентов Windows».
  4. Найдите клиент Telnet и установите флажок. Щелкните ОК.

Готово! Вы активировали клиент Telnet в системе.

После завершения активации можно пропинговать порт с помощью telnet. Для этого:

1. Введите cmd в поиске в меню «Пуск». Щелкните на приложение Командная строка.

2. В окне командной строки введите

telnet [address] [port_number]

Где [address] — это домен или IP-адрес хоста, а [port_number] — это порт, который вы хотите проверить.

telnet

Выходные данные позволяют узнать, открыт ли порт и доступен ли он, иначе отображается сообщение об ошибке подключения.

Пинг определенного порта с помощью PowerShell

Чтобы проверить связь с портом с помощью PowerShell, выполните следующие действия:

1. Введите PowerShell в поиске в меню «Пуск». Щелкните приложение Windows PowerShell.

2. В окне командной строке PowerShell введите:

Test-NetConnection [address] -p [port_number]

PowerShell

Если порт открыт и соединение прошло успешно, проверка TCP прошла успешно. В противном случае появится предупреждающее сообщение о том, что TCP-соединение не удалось.

Заключение

Теперь вы знаете, как выполнить эхо-запрос и проверить, открыт ли порт, с помощью нескольких сетевых инструментов и утилит в Linux и Windows.

Источник

How to Ping a Specific Port Number

Ping is probably the most used tool for checking the network connection to a remote system. Using ping is very easy. You just use the command ping together with the IP address or URL of the remote server.

ping faebook.com PING faebook.com (157.240.24.20) 56(84) bytes of data. 64 bytes from edge-star-shv-01-sin2.facebook.com (157.240.24.20): icmp_seq=1 ttl=51 time=307 ms 64 bytes from edge-star-shv-01-sin2.facebook.com (157.240.24.20): icmp_seq=2 ttl=51 time=225 ms

But what is the default port for the ping command? The answer is none.

Ping is based on ICMP, not TCP or UDP and ICMP protocol doesn’t have port numbers.

So how do you ping a specific port number of the remote server?

You cannot do that with the ping command. However, there are other tools that allow you to ping specific TCP or UDP ports.

Let me show you a couple of such tools and how to use them for pinging a given port number.

Ping specific port with Nmap

Nmap is a network scanning tool. While you can do a lot with Nmap, I’ll show you how to use it for pinging a specific port.

Читайте также:  Root права linux команда

But first, make sure that you have Nmap installed on your system. On Debian/Ubuntu based distributions, you can use the command below to install Nmap.

Once you have made sure that you have Nmap installed, you can use it in the following manner to ping a port:

The output will be something like this:

Starting Nmap 7.60 ( https://nmap.org ) at 2019-01-07 10:40 IST Nmap scan report for facebook.com (157.240.24.35) Host is up (0.49s latency). Other addresses for facebook.com (not scanned): 2a03:2880:f10c:83:face:b00c:0:25de rDNS record for 157.240.24.35: edge-star-mini-shv-01-sin2.facebook.com PORT STATE SERVICE 443/tcp open https Nmap done: 1 IP address (1 host up) scanned in 10.35 seconds

As you can see in the output, the server is up and it responded that the port number 443 of type TCP is open.

If you want to scan more than one ports, you can do that as well. For example, you can provide a range of port numbers like this:

The output will provide information on each individual port:

Starting Nmap 7.60 ( https://nmap.org ) at 2019-01-07 10:48 IST Nmap scan report for facebook.com (157.240.24.35) Host is up (0.34s latency). Other addresses for facebook.com (not scanned): 2a03:2880:f139:183:face:b00c:0:25de rDNS record for 157.240.24.35: edge-star-mini-shv-01-sin2.facebook.com 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 Nmap done: 1 IP address (1 host up) scanned in 4.49 seconds

You may also use the port name instead of the port number:

The output remains the same as the previous command.

If you want to specifically ping the TCP port, you can specify that as well:

nmap -p 443 -sT facebook.com
nmap -p 443 -sU facebook.com

Nmap is not the only tool. You can use some other tools as well.

Using telnet to ping a specific port on remote server

Telnet is a remote connection tool similar to SSH however SSH is more secure by design than Telnet.

Before using Telnet, you should make sure that it is installed. On Debian/Ubuntu, you can use this command to install Telnet:

Once you have Telnet, you can use it to connect to a specific port of a remote system.

If it’s successful, you should see an output like this:

telnet facebook.com 443 Trying 157.240.24.35… Connected to facebook.com. Escape character is '^]'.

You can close the connection using the keyboard shortcut Ctrl+] or simply press Ctrl+C.

Why there is no response from the port?

All the examples I showed so far had a successful response. But what if there is no response. What does it mean?

There could be a few possible reasons why I port may not respond.

  • There are no services listening to the port so there is nothing that will respond.
  • A firewall is blocking the incoming traffic on the specific port.
  • There is actually a network connection issue between you and the server in question.

I hope you liked this tutorial and learned how to ping a specific port number. If you have any questions or suggestions, please leave a comment below.

Источник

Оцените статью
Adblock
detector