Linux ping one time

Linux Ping Command Explained with Examples

Here are some of the most common usages of ping command in Linux along with their explanation.

Ping is one of the most commonly used networking commands in Linux and other operating systems.

Ping is mainly used to check if a remote host is reachable or not. The remote host could be a web server, your router or a system on your local network.

How does ping work? It actually sends small ICMP packets to the remote host and waits for the response. If the host is up, you should see a response.

It’s like the sonar technology used in submarines. The submarines send pulses of audio signal and wait for the echo to return.

So, how do you use Ping in Linux? What are different Ping command options? Let me show you some of the common usages of the Ping command.

Using ping command in Linux

Most Linux distributions come with this command. But it may not be available in containers. To install Ping on Ubuntu or other such systems, you’ll have to install the iputils-ping package.

Once you have it available on your system, you can use ping command with either the IP address or the hostname/URL.

Suppose I ping Google. It will send ICMP packets of size 56 bytes to google.com.

ping google.com PING google.com (108.177.122.102) 56(84) bytes of data. 64 bytes from 108.177.122.102 (108.177.122.102): icmp_seq=1 ttl=42 time=325 ms 64 bytes from 108.177.122.102 (108.177.122.102): icmp_seq=2 ttl=42 time=387 ms 64 bytes from 108.177.122.102 (108.177.122.102): icmp_seq=3 ttl=42 time=319 ms 64 bytes from 108.177.122.102 (108.177.122.102): icmp_seq=4 ttl=42 time=321 ms ^C --- google.com ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 3002ms rtt min/avg/max/mdev = 319.697/338.496/387.785/28.527 ms

You have to manually stop the ping command else it will keep on running. You can use the Ctrl+C terminal shortcut to stop the ping command in Linux, as I did in the above example.

When you stop the ping command, it presents you with a summary of the transmission. You can see stats like the number of ICMP packets transmitted, received packets, lost packets etc.

Now that you know how to ping in Linux, let’s see some of the other ping command options.

Send only N number of packets

If you don’t want the ping command to run forever without manually stopping it, you can use the -c option.

Читайте также:  Linux kernel get current

With this, you can specify the number of packets the ping command should send before stopping automatically.

ping -c 2 104.248.179.115 PING 104.248.179.115 (104.248.179.115) 56(84) bytes of data. 64 bytes from 104.248.179.115: icmp_seq=1 ttl=50 time=315 ms 64 bytes from 104.248.179.115: icmp_seq=2 ttl=50 time=423 ms --- 104.248.179.115 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1000ms rtt min/avg/max/mdev = 315.208/369.190/423.172/53.982 ms

Send ping only for a limited time

Apart from setting the number of packets to send, you can also set for how long the packets will be sent.

For example, if you want to send ping packets for only 5 seconds, you can use it like this:

ping -w 5 google.com PING google.com (64.233.177.138) 56(84) bytes of data. 64 bytes from yx-in-f138.1e100.net (64.233.177.138): icmp_seq=1 ttl=40 time=407 ms 64 bytes from yx-in-f138.1e100.net (64.233.177.138): icmp_seq=2 ttl=40 time=320 ms 64 bytes from yx-in-f138.1e100.net (64.233.177.138): icmp_seq=3 ttl=40 time=323 ms 64 bytes from yx-in-f138.1e100.net (64.233.177.138): icmp_seq=4 ttl=40 time=472 ms 64 bytes from yx-in-f138.1e100.net (64.233.177.138): icmp_seq=5 ttl=40 time=406 ms --- google.com ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4002ms rtt min/avg/max/mdev = 320.634/385.993/472.056/57.309 ms

Change the time interval between two pings

By default, ping sends the packets at an interval of one second. You can change this time interval with the -i option.

To send the ICMP packets with an interval of 3 seconds, you can use Ping command like this:

You can decrease the time interval between pings as well.

However, if you try to decrease the time interval below 0.2 seconds (200 ms), you’ll see an error:

ping -i 0.1 31.13.90.36 PING 31.13.90.36 (31.13.90.36) 56(84) bytes of data. ping: cannot flood; minimal interval allowed for user is 200ms

Don’t worry. You can still ping with an interval less than 200 ms. But to do that, you need to use the ping with root privileges.

sudo ping -i 0.1 31.13.90.36 PING 31.13.90.36 (31.13.90.36) 56(84) bytes of data. 64 bytes from 31.13.90.36: icmp_seq=1 ttl=49 time=470 ms 64 bytes from 31.13.90.36: icmp_seq=2 ttl=49 time=372 ms

Change the packet size

The default ICMP packet size sent by Ping is 56 bytes. This can be changed as well with the help of -s command.

ping -s 100 31.13.90.36 PING 31.13.90.36 (31.13.90.36) 100(128) bytes of data. 108 bytes from 31.13.90.36: icmp_seq=1 ttl=49 time=234 ms 108 bytes from 31.13.90.36: icmp_seq=2 ttl=49 time=257 ms 108 bytes from 31.13.90.36: icmp_seq=3 ttl=49 time=280 ms ^C --- 31.13.90.36 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2002ms rtt min/avg/max/mdev = 234.208/257.352/280.424/18.867 ms

DoS attack with Ping flooding aka Ping of Death

One of the simplest DoS attack is the Ping of Death. In this kind of attack, the attacker sends a large number of ping request in a very short span of time. If the server is not well configured, it will crumble in handling the ping request and the website will go down.

Читайте также:  Linux list all connection

The ping command has built-in ‘feature’ for this. It’s called ping flooding and it can be achieved with the -f option. You’ll need sudo rights to run this option with zero interval.

sudo ping -f google.com PING google.com (108.177.122.101) 56(84) bytes of data. …………………..^C --- google.com ping statistics --- 1436 packets transmitted, 1413 received, 1% packet loss, time 22837ms rtt min/avg/max/mdev = 313.887/326.102/388.178/7.464 ms, pipe 26, ipg/ewma 15.914/323.456 ms

When you run this command, you’ll see some dots appearing and disappearing in the output. Every single ‘.’ denotes a request whereas the reply is a backspace (this is why dots disappear).

This flood ping option is useful in testing the load capacity of a server.

You cannot use this command to ping a specific port. You’ll have to use some other tool like nmap for this purpose.

Bonus Tip: Send audible pings

You can send audible pings with -a option. With this, you’ll hear a beep for every successful ping.

Note that not all Linux distributions are configured to make the beep noise. I tested it on Ubuntu 18.04 and I could hear the beep.

Troubleshooting Ping command

So far what we have seen is the successful examples of the ping command. But that won’t happen all the time. Let’s see some of the common errors you may see and understand the reason for those errors.

No reply for ping

You might notice that certain hosts do not reply to the ping request. It seems like the ping command has hanged because there is no response. The command just stays there, it doesn’t even times out.

If you terminate the ping command, you’ll see some strange statistics.

ping intel.com PING intel.com (13.91.95.74) 56(84) bytes of data. ^C --- intel.com ping statistics --- 100 packets transmitted, 0 received, 100% packet loss, time 101362m

As you can see, 100 packets were transmitted but no response was received for any of them.

It’s most likely because some servers discard the ICMP packets. This is a security measure to avoid ping flooding.

Destination host unreachable

This error can occur because of one of two reasons:

  • Either the local system has no route to the remote host
  • or the end point router has no route to the remote host

If you only see the ‘destination host unreachable’ error, this means your system couldn’t find a route to the remote host.

On the other hand, if you see the error in the “Reply from ” part of the reply, it means that the packet was sent outside of your network but it couldn’t reach the destination.

Sometimes servers also block the ICMP traffic that could show this error.

Читайте также:  Astra linux сеть недоступна

Request times out

This error means that the packets reached the remote server but the reply could not reach your system. The issue could be lost packets or routing errors.

Ready to Ping?

I hope this tutorial helped you in understanding the Linux ping command better.

If you have questions or suggestions, please leave a message in the comment section.

Источник

Команда ping: подробный обзор

Ping – утилита командной строки, которая нужна для проверки подключения к другому компьютеру на уровне IP. Принцип работы очень простой: команда ping ip отправляет серию небольших пакетов данных на указанное устройство, а затем показывает время ответа.

Ping – основная команда TCP/IP, которая используется для устранения неполадок подключения, доступности и разрешения имени. Она также позволяет узнать имя и IP-адрес компьютера.

Синтаксис команды ping

Команда ping в Windows имеет следующие параметры, которые позволяют решать разные задачи:

ping [/t] [/a] [/n ] [/l ] [/f] [/I ] [/v ] [/r ] [/s ] [] [/w ] [/R] [/S ] [/4] [/6]

Чтобы посмотреть в командной строке (cmd) ping-команды, вызовите справку:

Справка Ping на Windows

На Linux параметры команды отличаются. Чтобы посмотреть доступные опции, выполните в терминале команду:

Справка ping

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

Простая проверка доступности

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

ping google.com // вместо домена можно указать IP-адрес

Windows отправит только 4 запроса, после чего выдаст статистику для указанного адреса. Можно убрать это ограничение, указав параметр -t.

Чтобы прервать отправку и получить статистику, нажимаем сочетание клавиш Ctrl+C.

Проверка доступности сервера

По умолчанию команда ping IP-адреса на Linux посылает пакеты, пока вы не прервете их отправку вручную с помощью сочетания клавиш Ctrl+C. Чтобы ограничить количество, укажем нужное число. Например:

ping -c 3 google.com // будет отправлено 3 пакета

Изменение интервала между отправкой пакетов

По умолчанию пакеты отправляются с интервалом в одну секунду. Но можно установить другое время.

ping -i 5 IP-адрес // 5 секунд между отправкой пакетов ping -i 0.2 IP-адрес // 2 миллисекунды между отправкой пакетов

Для установки значений меньше 0.2 секунды требуются права суперпользователя (sudo).

Массовая отправка пакетов для нагрузочного тестирования

Эта возможность также доступна только суперпользователям:

ping -f IP-адрес // за секунду будут отправлены сотни тысяч запросов

Изменение размера пакета

По умолчанию размер пакета – 32 байта. Можно установить другой размер:

$ ping -s 100 IP-адрес // значения указываются в байтах

Включение звукового сигнала

Если ответа от хоста нет, отправляем эту команду:

Затем начинаем искать причину сбоя. После ее устранения воспроизведется звуковой сигнал. Он говорит о том, что хост теперь отвечает.

Вывод статистики ping

Чтобы не засорять терминал лишней информацией, пропустим ответы хоста и сразу получим статистику:

А можно, наоборот, получать статистику выполнения без прерывания команды. Для этого нужно нажать сочетание клавиш CTRL + |.

Источник

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