Can ping linux server

Команда ping в Linux

Всем знакомы ситуации, когда интернет на компьютере неожиданно разрывается, такое поведение можно наблюдать при использовании ADSL модемов, Wifi на большом расстоянии, GSM и других подобных ненадежных технологий. Быстро выяснить есть ли на компьютере интернет можно с помощью утилиты ping.

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

Как работает ping?

Утилита ping — это очень простой инструмент для диагностики сети. Она позволяет проверить доступен удаленный хост или нет и все. Для этого утилита проверяет, может ли хост отвечать на сетевые запросы с помощью протокола ICMP.

Надеюсь, не нужно говорить, что все данные по сети передаются в виде небольших пакетов. Программа передает небольшой пакет с данными ICMP и ожидает получить обратно пакет ответа, если получает, то считается что удаленный узел доступен. ICMP или Internet Control Message Protocol — это надстройка над протоколом IP, которая используется для передачи служебных сообщений и сообщений и ошибках.

Протокол ICMP может передавать только два типа пакетов — это сообщения с отчетами про ошибки и сообщения запросов. В свою очередь, сообщения запросов делятся на:

Попытаемся разобраться что делает команда ping. Итак, когда вы отправляете запрос ping удаленному узлу, утилита устанавливает для каждого пакета уникальный идентификатор, а также TTL и время отправки пакета. Если хост доступен, он отправляет ответ, на основе времени отправки утилита может вычислить время прохождения пакета туда и обратно. Затем отправляется следующий пакет. В конце рассчитывается общее количество отправленных и принятых пакетов, процент потерь и другие данные.

Команда Ping

Теперь нам осталось немного попрактиковаться. Но перед тем, как мы перейдем к практике давайте рассмотрим синтаксис команды и ее опции. Синтаксис довольно прост:

$ ping опции адрес_узла

Формат команды ping очень прост. В качестве адреса узла можно передавать как ip адрес, так и доменное имя. Опции настраивают поведение утилиты. Рассмотрим основные из них:

  • -4 — использовать только ipv4 (по умолчанию);
  • -6 — использовать только ipv6;
  • -A — адаптивный режим, время между отправками пакета адаптируется к времени передачи и приема пакета, но не меньше чем 200мс;
  • -b — разрешить ping широковещательного адреса;
  • — количество пакетов, которые нужно отправить;
  • -D — выводить время в виде UNIX timestamp;
  • -f — режим флуда, в этом режиме пакеты передаются без задержек, может использоваться для совершения DoS атак на отдельные узлы. Количество точек, которые выводит утилита обозначает количество потерянных пакетов;
  • -i — интервал в секундах между отправкой пакетов;
  • -I — использовать этот сетевой интерфейс для отправки пакетов;
  • -l — режим перегрузки, отправляется очень много пакетов и система не следит за ответными пакетами;
  • -n — не получать домены для ip адресов;
  • -r — игнорировать таблицы маршрутизации и отправить пакет на указанный интерфейс;
  • -s — размер одного пакета;
  • -t — установить TTL вручную;
  • -v — более подробный вывод.
Читайте также:  Linux kernel version linux mint

Теперь, когда мы рассмотрели основные параметры команды ping и ее синтаксис, пришло время практики, дальше поговорим о том, как сделать ping определенного узла в Linux.

Как пользоваться Ping?

Для проверки работоспособности сети часто используется программа ping любого сайта, который всегда доступен, например, google.com или еще проще и короче ya.ru. Вам будет достаточно передать утилите в параметрах этот адрес, она сама найдет ip и сделает все нужное:

Как я и писал выше, для каждого пакета выводится уникальный идентификатор icmp_seq, количество узлов до целевого узла ttl и время, потраченное на доставку пакета time. Чтобы остановить ping нажмите сочетание клавиш Ctrl+C. В конце утилита вывела общую статистику:

  • packets transmitted — отправлено пакетов;
  • received — получено пакетов;
  • packet loss — процент потерянных пакетов;
  • time — обще время работы;
    rtt min/avg/max/mdev — минимальное время/среднее время/максимальное время/квадратичное отклонение.

Если выполнение команды ping не остановить, то пакеты могут отправляться очень долгое время, это создает дополнительную нагрузку на сервер и поэтому не желательно. Вы можете сразу в вызове команды ограничить количество отправляемых пакетов с помощью опции -c:

Точно так же как мы выполняем ping для домена, можно указать ip адрес напрямую. Это позволяет проверить есть ли сеть когда неверно настроены серверы DNS. Например:

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

По умолчанию, в обычном режиме, каждый следующий пакет отправляется, когда получен ответ на предыдущий. Но вы можете сами установить интервал между отправкой пакетов -i:

Здесь программа ping выполняет так званный, настраиваемый флуд, вы указываете с какой интенсивностью нужно отправлять пакеты. С помощью опции -D вы можете увидеть Unix Timestamp для каждого сообщения:

Выводы

В этой статье мы рассмотрели что такое команда ping в linux, как ее использовать основные параметры и методы применения. Этот очень простой инструмент можно применять для тестирования неполадок сети и их исправления. В этом плане утилита может стать незаменимой.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to ping IP and port from Windows or Linux

One of the things I do the most when troubleshooting deployments of services exposing data to the internet is pinging the IP and port where the service is supposed to be alive. In this tutorial, I will show you how to ping IP and port on Linux and Windows.

I think most system administrators know the commands for this, but if you like me normally don’t work like an IT admin (at least not anymore) I tend to forget the commands. Due to that, I have written this article as a reference for myself but also for everyone else, who is in need of pinging services they expect at a location.

Often it’s enough to just ping an IP to validate that you got “life” on the server. However if you like me often got many services running on one server (often when using Docker), I need to ping the specific port number on the server. One of the Kubernetes clusters I manage is running more than 100 services and here I use it a lot.

Читайте также:  Linux kernel module symbols

In this article/reference post, I will show you how to ping IP and port on your Windows or Linux machine using different commands in the terminal (CLI).

Ping IP and port using Telnet

This is my favorite when working on both Windows and Linux. I also think that it’s the easiest one to use and it’s called Telnet. You can with a simple command using Telnet ping IP and port on the remote server you would like to check.

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:

Install Telnet on Linux

If you are working on a Linux Server or Desktop, you can use the below command to install Telnet on that machine:

Install Telnet on Windows

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:

  1. Click on Start.
  2. Select Control Panel.
  3. Choose Programs and Features.
  4. Click Turn Windows features on or off.
  5. Select the Telnet Client option.
  6. Click OK.
    A dialog box appears to confirm installation when it’s done. The telnet command should now be available in your Command Prompt. Remember to restart your CMD window.

Ping IP and port with Telnet example

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.

Ping IP and port using Nmap

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.

Читайте также:  Linux gui disk utility

If you get an error telling you that Nmap is not available on your computer/server, you would have to install it.

Install Nmap on Linux

To install Nmap on your Linux machine, you can use the below command:

Install Nmap on Windows

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.

Ping IP and port using Nmap

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.

Ping IP and port using PowerShell

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.

Summary

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!

Christian Schou

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.

Источник

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