«Для чего в команде ping используются опции Loose, Strict, Record, Timestamp и Verbose?» — такой вопрос мне недавно встретился в вендорном экзамене. Они позволяют влиять на маршрутизацию ICMP пакетов и собирать информацию о транзитных L3-устройствах. Но занимаясь сетевыми технологиями уже достаточно давно, я почти никогда их не использовал.
Мне стало не совсем понятно, почему такой вопрос вообще присутствует в тесте. Вернувшись домой, решил узнать, вдруг я действительно постоянно упускаю из виду что-то важное?
Утилита ping нам всем хорошо знакома. Помимо стандартного «ping 8.8.8.8», можно использовать различные опции, среди которых присутствуют интересующие нас. Их наименование и описание у вендоров примерно одинаковое.
Из наиболее часто используемых я бы отметил следующие.
- Количество отправляемых пакетов
Вместо заданного количества пакетов по умолчанию (например, в Windows — четыре, в оборудовании Cisco — пять), мы можем отправить нужное. Сюда же можно отнести многими любимую опцию «-t» в ОС Windows, которая запускает бесконечную отправку пакетов. - Интерфейс источника
В первую очередь актуально для сетевого оборудования. По умолчанию, при использовании команды ping устройство отправляет пакет с адресом ближайшего интерфейса к точке назначения. В случае тестирования функций NAT или проверки VPN, возникает необходимость отправлять ICMP пакеты с другого интерфейса. Ещё один классический пример: как доказать коллеге, что у него включён файрвол на хосте, а не сеть глючит. Запускаем ping с ядра сети без указания интерфейса – пингуется. С указанием неближайшего интерфейса – не пингуется. - Установка DF-бита
Пакет с установленным DF-битом (=1) не может фрагментироваться. Данную опцию удобно использовать для определения максимально допустимого размера кадра (MTU) между двумя точками. Обычно используется в связке параметрами ниже. - Размер пакета
Можно варьировать размер пакета. Вместе с установкой DF-бита помогает в определении MTU. Шлём большой пакет – 1500 байт. Не проходит. Шлём чуть меньше – 1300. Проходит. Шлём 1400. И так далее. В общем, метод дихотомии и MTU определён.
В Windows мы указываем размер сегмента данных ICMP пакета. На устройствах Cisco – размер пакета IP с учётом заголовков. - Вариация размера пакета в указанном диапазоне
Для тех, кто не любит метод дихотомии, может пригодиться данный режим. Мы указываем начальное значение размера пакета, конечное и шаг. Далее устройство отправляет пакеты, постепенно увеличивая их размер. Главное не забыть выставить DF-бит, а то всё насмарку.
За бортом остался ряд других опций (timeout, ToS и пр.), которыми лично я практически не пользуюсь.
Опции Loose, Strict, Record, Timestamp, Verbose включены в утилиту ping на многих сетевых устройствах. Есть поддержка в Windows.
Record (Record Route)
Пакет ICMP с опцией Record при прохождении через L3-устройства записывает IP-адреса исходящих интерфейсов. Делается это как в сторону пункта назначения, так и обратно. Это удобно, например, при диагностировании проблем, связанных с асинхронной маршрутизацией. Получается вроде traceroute, только лучше.
«Опции»
Слово «опции» я использую в двух контекстах: опции команды ping и опции в пакете ICMP. В случае ICMP, опции – это дополнительные параметры, которые устанавливаются в заголовке IPv4 (далее будем указывать просто IP) в поле Options. Поэтому корректнее, конечно, говорить про опции IP. ICMP просто их использует в своей работе.
Но рано радоваться: максимальное количество записей равно девяти. Причём в них входят данные об IP-адресах устройств в обе стороны. Обусловлено данное ограничением тем, что информация об IP-адресах сохраняется не в теле пакета, а в заголовке. Поле с опциями не может быть слишком большим. Оно ограничено 40 байтами. Нам, в конце концов, по сети нужно гонять полезные данные, а не заголовки. В этот объём помещается всего девять записей (4 байт на каждый IPv4 адрес). Оставшиеся (40-4*9)=4 байта уходят на отметку о типе опции, длине и пр. атрибутах. Напомню, максимальный размер всего заголовка IPv4 – 60 байт.
Запускаем с ПК под управлением ОС Windows ping с опцией Record Route (-r) до адреса 192.168.36.2:
C:\Users\user>ping -n 1 -r 9 192.168.36.2
Обмен пакетами с 192.168.36.2 по с 32 байтами данных:
Ответ от 192.168.36.2: число байт=32 время=12мс TTL=252
Маршрут: 192.168.31.2 ->
192.168.32.2 ->
192.168.34.2 ->
192.168.35.2 ->
192.168.36.2 ->
192.168.35.1 ->
192.168.33.1 ->
192.168.31.1 ->
192.168.20.1
Статистика Ping для 192.168.36.2:
Пакетов: отправлено = 1, получено = 1, потеряно = 0
(0% потерь)
Приблизительное время приема-передачи в мс:
Минимальное = 12мсек, Максимальное = 12 мсек, Среднее = 12 мсек
Пакeт ICMP Echo Request c выставленной опцией Record Route (Type = 7) в заголовке IP:
ICMP Echo Request доходит до получателя. По пути в него добавляются адреса транзитных устройств. Получатель берёт заполненные поля опции IP заголовка, копирует их в ICMP Echo Reply и отправляет назад. Пока ICMP Echo reply доберётся до инициатора пинга, он обрастёт записями обратного маршрута.
В ответном пакете ICMP Echo Reply, который получит ПК, опция Record Route будет уже заполнена:
Можно заметить, что в нашей сети имеет место ассиметричная маршрутизация.
Пример ping с опцией Record на сетевом оборудовании Cisco.
R1#ping
Protocol [ip]:
Target IP address: 192.168.36.2
Repeat count [5]: 1
Datagram size [100]:
Timeout in seconds [2]:
Extended commands [n]: y
Source address or interface:
Type of service [0]:
Set DF bit in IP header? [no]:
Validate reply data? [no]:
Data pattern [0xABCD]:
Loose, Strict, Record, Timestamp, Verbose[none]: R
Number of hops [ 9 ]:
Loose, Strict, Record, Timestamp, Verbose[RV]:
Sweep range of sizes [n]:
Type escape sequence to abort.
Sending 1, 100-byte ICMP Echos to 192.168.36.2, timeout is 2 seconds:
Packet sent with a source address of 192.168.20.1
Packet has IP options: Total option bytes= 39, padded length=40
Record route: <*>
(0.0.0.0)
(0.0.0.0)
(0.0.0.0)
(0.0.0.0)
(0.0.0.0)
(0.0.0.0)
(0.0.0.0)
(0.0.0.0)
(0.0.0.0)
Reply to request 0 (3 ms). Received packet has options
Total option bytes= 40, padded length=40
Record route:
(192.168.31.2)
(192.168.32.2)
(192.168.34.2)
(192.168.35.2)
(192.168.36.2)
(192.168.35.1)
(192.168.33.1)
(192.168.31.1)
(192.168.31.2) <*>
End of list
Success rate is 100 percent (1/1), round-trip min/avg/max = 3/3/3 ms
Timestamp
Когда пакет ICMP с опцией Timestamp проходит через L3-устройство, оно записывает в него метку с указанием текущего времени. Схема работы аналогична опции Record, только вместо адреса ставится время. Как и в предыдущем случае пакет может содержать только девять записей о времени (для ОС Windows – четыре, так как кроме временной метки, добавляется IP-адрес устройства).
Время в пакете указано в формате UNIX time. Анализ данных имеет хоть какой-то смысл, если все устройства синхронизированы по времени (в нашем примере этого нет).
Пример ping с опцией Timestamp (-s) на ПК под управлением ОС Windows.
C:\Users\user>ping -n 1 -s 4 192.168.36.2
Обмен пакетами с 192.168.36.2 по с 32 байтами данных:
Ответ от 192.168.36.2: число байт=32 время=4мс TTL=252
Отметка времени: 192.168.31.2 : 43990397 ->
192.168.32.2 : 43990389 ->
192.168.34.2 : 2187294073 ->
192.168.35.2 : 2190888543
Статистика Ping для 192.168.36.2:
Пакетов: отправлено = 1, получено = 1, потеряно = 0
(0% потерь)
Приблизительное время приема-передачи в мс:
Минимальное = 4мсек, Максимальное = 4 мсек, Среднее = 4 мсек
Strict (Strict Source Route)
При использовании данной опции задаётся список IP-адресов L3-устройств, через которые ICMP пакет обязательно должен пройти. Причём именно в той последовательности, которую мы указали. Записей, по традиции, максимум девять.
Работает опция просто: на каждом хопе IP-адрес назначения меняется на тот адрес, который мы указали при запуске утилиты ping.
Все адреса хранятся в заголовке IP нашего ICMP пакета. Поэтому каждое транзитное устройство может их подсмотреть. Такая схема позволяет обходить текущие правила маршрутизации на каждом устройстве, так как фактически имеем пересылку пакета на соседнее устройство.
В нашей схеме R2 имеет маршрут в сеть 192.168.36.0/24 через R3. Но так как у нас жёстко прописаны устройства в опциях ICMP пакета, R2 передаст его напрямую на R4.
Запускаем утилиту ping с опцией -k (Strict Source Route) в ОС Windows и прописываем адреса устройств.
C:\Users\user>ping –n 1 -k 192.168.20.1 192.168.31.1 192.168.33.1 192.168.35.1 192.168.36.2
Обмен пакетами с 192.168.36.2 по с 32 байтами данных:
Ответ от 192.168.36.2: число байт=32 время=5мс TTL=252
Маршрут: 192.168.35.1 ->
192.168.33.1 ->
192.168.31.1 ->
192.168.20.1
Статистика Ping для 192.168.36.2:
Пакетов: отправлено = 1, получено = 1, потеряно = 0
(0% потерь)
Приблизительное время приема-передачи в мс:
Минимальное = 5мсек, Максимальное = 5 мсек, Среднее = 5 мсек
Пакeт ICMP Echo Request c выставленной опцией Strict Source Route (Type = 137) в заголовке IP на нашем ПК выглядит следующим образом:
ПК подставил 192.168.20.1 в качестве адреса получателя. Остальные адреса транзитных устройств благополучно запаковал в поля опции IP (записи Source Route). Адрес конечного устройства добавил в запись Destination.
Этот же пакет, после того, как он минует R1:
IP-адрес отправителя остался без изменений. IP-адрес получателя поменялся на новый – 192.168.31.1. Это значение взято из поля Source Route, когда пакет ICMP только поступил на R1.
Важно отметить, что R1 занёс в поле опций новую запись — Recorded Route. Туда подставлен IP-адрес интерфейса R1. Данное поле понадобится, чтобы ответный пакет (ICMP Echo reply) вернулся по тому же маршруту, что и ICMP Echo request. Точно также будут поступать и остальные устройства. Поэтому, когда пакет ICMP попадёт на R5, в опции Strict Source Route будет содержаться список IP-адресов интересов, через которые должен пройти ответный пакет.
ICMP Echo reply, полученный ПК:
Поле Recorded Route переписывается по мере прохождения пакета ICMP Echo reply, так как там всегда указан адрес исходящего интерфейса для текущего пакета. Поэтому R1, когда получит ICMP Echo reply, заменит 192.168.31.2 на 192.168.20.1.
Если в команде ping мы опустим один из адресов, например, последний (192.168.35.1 – R5), R4 должен будет отправить пакет сразу на устройство с адресом 192.168.36.2. Но так как эта сеть не является для него локальной, R4 отрапортует о том, что заданный узел недостижим. Маршрутизировать пакет по обычным правилам он не будет.
Для обработки опции Record на сетевом оборудовании должен быть включен режим source routing. Например, на оборудовании Cisco он включён по умолчанию.
Loose (Loose Source Route)
Данная опция по сути очень похожа на опцию Strict. Но, в отличии от Strict, в опции Loose задаётся не жёсткий маршрут движения ICMP пакета, а лишь выборочные устройства. Т.е. пакет может маршрутизироваться и другими устройствами. Максимальное количество адресов – девять.
Схема работы аналогична предыдущему случаю. Разница в том, что пакет с опцией Loose может маршрутизироваться транзитными устройствами по обычным правилам.
Запускаем утилиту ping с опцией -j (Loose Source Route) в ОС Windows и прописываем адреса устройств.
C:\Users\user>ping -n 1 -j 192.168.32.1 192.168.36.2
Обмен пакетами с 192.168.36.2 по с 32 байтами данных:
Ответ от 192.168.36.2: число байт=32 время=4мс TTL=250
Маршрут: 192.168.32.1
Статистика Ping для 192.168.36.2:
Пакетов: отправлено = 1, получено = 1, потеряно = 0
(0% потерь)
Приблизительное время приема-передачи в мс:
Минимальное = 4мсек, Максимальное = 4 мсек, Среднее = 4 мсек
Пакeт ICMP Echo Request c выставленной опцией Loose Source Route (Type = 131) в заголовке IP на нашем ПК выглядит так:
ПК подставил адрес R3 (192.168.32.1) в качестве получателя. При этом адрес конечного устройства R5 (192.168.36.2) указал в опции IP (запись Destination). Далее пакет маршрутизируется в сети по обычным правилам, пока не попадёт на R3. R3 подставит в качестве адреса назначения адрес R5 и в опциях пропишет свой адрес, через который должен будет вернуться ответный пакет (запись Recorded Route). После чего отправит его в сеть.
Ответный пакет ICMP Echo reply особого интереса не представляет, так как аналогичен ранее рассмотренным. В опциях будет указан адрес исходящего интерфейса R3 (запись Recorded Route), через который прошел пакет.
Verbose
Данная опция активируется автоматически при выборе любой из ранее описанных. Предоставляет более детальный вывод информации на экран. На сам пакет ICMP она никак не влияет. В Windows в команде ping такой опции нет.
Чтобы мы могли воспользоваться этими опциями, промежуточное оборудование должно их поддерживать. С этим проблем не будет. К новшествам мира ИТ относить весь этот «rocket science» не приходится. Напрашивается вывод: опции Loose, Strict, Record, Timestamp могут быть полезны, даже с учётом ограничения в «девять». Если бы не следующие нюансы, связанные с безопасностью.
Первое. Опции Record и Timestamp могут благополучно использоваться для проведения разведки в сети. С их помощью можно исследовать топологию сети, получить отпечатки, по которым определить ОС и тип устройства, через которые проходил пакет с данными опциями.
Второе. Опции Loose и Strict позволяют управлять движением пакета, игнорируя стандартные правила маршрутизации. Это предоставляет широкие возможности для попыток проникновения в различные сегменты сети, куда в случае обычной маршрутизации доступа не должно быть. Также возможно проведение разведки для анализа топологии сети. Проведение атак по утилизированию полосы пропускания на определённых сегментах сети. Вариантов много.
Третье. Часть сетевого оборудования обрабатывает пакеты с установленными опциями программным образом на уровне control-plane (без использования различных схем оптимизации маршрутизации трафика), что безусловно нагружает ЦПУ. А значит есть возможность осуществить DoS атаку на такое устройство.
Многие вендоры (есть даже отдельное RFC 7126) рекомендуют пакеты с указанными опциями никак не обрабатывать. Варианты предлагают разные. Вплоть до отбрасывания таких пакетов. Правда у некоторых из производителей бывают диссонансы: с одной стороны рекомендуем отбрасывать такие пакеты, с другой — «Record is a very useful option».
Быстрая попытка проверить соответствие этим рекомендациям у пары интернет-провайдеров показали, что часть опций всё-таки работает. Но source routing отключён везде.
Получается интересный вывод. Опции Loose, Strict, Timestamp, Record могут быть полезны при диагностике проблем в сети. Но вопрос безопасности нивелирует это.
В итоге у меня всё-таки осталось чувство непонимания. Почему озвученный в начале вопрос присутствовал в тесте? Относительно полезна опция Record и то при небольшой глубине сети. Остальные опции под вопросом.
Напоследок небольшой опрос. Всем хорошего дня!
Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.
Пользуетесь ли Вы опциями Loose, Strict, Timestamp, Record?
1.35% Я их просто блокирую6
23.99% Да, жена заставляет107
Проголосовали 446 пользователей. Воздержались 76 пользователей.
In this article you’ll find:
- How to Ping with Timestamps
- Best Ping Tools for Accurate Checks
- hrPing
- PingWiz
- PingInfoView
- PowerPing
- Bping
- Windows Ping Command
- Ping from PowerShell
If you’re troubleshooting network or internet connections, using the built-in Windows Ping utility can be a quick way to check connectivity. However, by default, Ping doesn’t show timestamps.
This guide highlights 7 tools to add timestamps and continuously ping addresses, with options to log results to a text file.
How to ping with timestamps
- Open Command Prompt
PressWindows + R
, typecmd
, and hitEnter
. - Enter Ping Command
Use this format:ping -t [hostname] | cmd /q /v /c "(pause&pause)>nul & for /l %a in () do (set /p "data=" && echo(!date! !time! !data!)&ping -n 2 [hostname]>nul" >C:\pingtest.txt
- Continuous Ping
The-t
flag keeps pinging. - Timestamp Included
echo(!date! !time!)
adds the date and time. - Save to File
>C:\pingtest.txt
saves the result. - Change Host
Replace[hostname]
with your target. - Stop
PressCtrl + C
to stop.
In addition to a timestamp, it’s also useful to be able to continuously ping for reliability over a period of time and optionally send the results to a text file for logging purposes. Here we show you 7 ways to timestamp pings as well as sending a continuous set of ping results to a text file. Make sure to run Command Prompt or batch files as Administrator to avoid issues as some tools require it.
Best ping tools for accurate checks
1. hrPing
hrPing is by cFos Software who also develop the cFosSpeed internet accelerator application.
The hrPing tool itself is one of the most advanced of its type and allows you to configure just about anything you want with regards to what you ping, how often you ping it and when.
There are around 40 different command line arguments available so reading the documentation is recommended for more advanced usage.
Luckily you only need a few of the available arguments to ping with a timestamp and optionally send the results to a text file. Use -t to loop the ping until you manually stop it, -T adds the time and date stamp while -F [filename] allows saving the output to a text file (include -q to output only to file).
hrping -t -T -F D:\pingtest.txt raymond.cc
To ping a specific number of times instead of continuously, substitute -t for -n [number]. Also, you can use -s [milliseconds] to reduce the ping frequency from half a second to something a bit slower. An additional argument of -gg will open a separate window with a small graph of ping response times (pictured above), useful if you have a particular interest in the speed of the ping responses.
Download hrPING
2. PingWiz
For ease of use, it doesn’t get much simpler than PingWiz because it’s like a cut-down version of the Windows ping command that timestamps each ping request automatically without additional arguments.
Simply use pingwiz [hostname] and it will add the time and date with pinging the host four times. Adding /t will loop the pings continuously until you press Ctrl+C or /n:[number] will ping the specified number of times. A manual redirection to an output file is required if you want to send the ping results to a log file.
pingwiz raymond.cc /t >C:\pingtest.txt
There are only two other commands available in PingWiz in addition to those above, the ping timeout in seconds (/w) and the number of bytes to send (/b).
Unlike hrPING, this tool will not show ping results in the console window and redirect to a file at the same time.
Download PingWiz
3. PingInfoView
PingInfoView by Nirsoft is a little different to the other tools because it works from a graphical user interface. This makes it easy to spot ping errors more quickly if you are actively monitoring and watching for issues because they will show up in the user interface as red entries. PingInfoView does have some command line options but they are to control ping rates and file saving in the user interface.
On launch, PingInfoView will popup a window where you can add one or a number of addresses to monitor, the ping timeout and the repeat rate (default is to ping every 5 seconds). Press OK and the main window will appear. The upper pane is the monitored hosts list with statistics about the ping results like success/fail rates, min/max/average times and succeed/fail times.
Click on a host in the upper pane to show the individual time stamped ping results at the bottom as they come in. When you have finished monitoring press the Stop button on the toolbar. The lower pane results can be saved to a text file, click on any entry and press Ctrl+A to highlight everything, right click and choose “Save Selected Items”, then save as a tabbed text, delimited text or HTML file.
Download PingInfoView
4. PowerPing
PowerPing is an open source tool hosted on GitHub. What sets this tool apart from other command line programs is there’s a splash of color in the ping results so you can more easily spot successes and failures. There are also around 40 commands available to control the pinging process and perform a few extra functions.
Typing PowerPing and using just the hostname will perform a standard five pings, including –t will make it continuous. The all important timestamp option is added with –ts which will put the time at the end of the line. There is no date in PowerPing’s timestamp so you may have to try another tool if that is something you need. To adjust the ping interval, use –in [milliseconds].
PowerPing –t –ts –in 2000 raymond.cc
If you want a more visual display, PowerPing has a graph option (–g) that will show in the console window instead of the text. There’s also a few general network features such as getting the location for an address, a whois lookup for an address and a whoami for the current host. You can also turn the colors off or enable a beep for timeouts. To send the output to a file, use the standard redirection method of >filename.
Download PowerPing
5. Bping
By default, Bping will give an audible beep or play a custom WAV file every time it pings and receives a reply. However, this option can be changed so Bping only beeps on a failure. If the Bping output is being redirected to a file, it can be left to beep or you can turn it off. It can also scan for and show other computers on the network with the option to show freely available IP addresses.
To add a timestamp to the command use the -u argument, -q will completely disable the beep if you find it annoying. Pinging will be continuous by default unless you use -n=number. Bping will ping Google DNS (8.8.8.8) if you don’t supply an address or hostname. As there is no command to output to file, redirect the results using >filename or >>filename to append to an existing file.
bping raymond.cc -u -q >C:\pingtest.text
Some other useful commands are -d which will only beep if the ping fails, -s which will scan the local network for devices, -a will show all available addresses on the network, and -c will add a count number to each ping. If you don’t use the number option the Bping command will have to be exited from the command line with Ctrl+C because it will continuously ping until you exit the program.
Download Bping
6. Windows Ping Command
Although the Windows Ping command has no built-in function to date and timestamp the result of each ping, with a bit of effort you can get it to do that. It’s quite useful if you specifically need to use the Windows Ping command. The following was found on StackOverflow and looks complicated but seems to work quite well.
ping -t raymond.cc|cmd /q /v /c “(pause&pause)>nul & for /l %a in () do (set /p “data=” && echo(!date! !time! !data!)&ping -n 2 raymond.cc>nul” >C:\pingtest.txt
The above will continuously ping the address with a time and date and an output log file, press Ctrl+C to end the session. If you wish to add the line to a batch script substitute the “%a” for “%%a” in the middle of the command. There are of course variations of inserting the time and date into the Windows Ping, feel free to share them in the comments. Remove the redirection to an output file if you want to show the results in the console window.
7. Ping From PowerShell
There are some dedicated PowerShell commands for pinging remote computers like Test-Connection and Test-NetConnection, but the standard Ping command also works as normal. As with Command Prompt, PowerShell requires you to manually insert a timestamp.
Test-Connection -count 999999999 -delay 2 raymond.cc | select @{n=’Date/Time’;e={Get-Date}},Address , IPv4Address ,ResponseTime >C:\pingtest.txt
As Test-Connection does not have an infinite loop switch we have to set a large count time. An optional delay of two seconds between pings helps extend the time even further. For using the Ping command:
Ping.exe -t raymond.cc | ForEach {“{0} – {1}” -f (Get-Date),$_} >C:\pingtest.txt
The above does pretty much the same as Ping from Command Prompt in method six. One of the advantages PowerShell has over Command Prompt is the ability to send the output in two different directions at once. That gives you the option to view the ping results in the console window and output to a file at the same time.
Ping.exe -t raymond.cc | ForEach {“{0} – {1}” -f (Get-Date),$_} | Tee C:\pingtest.txt
All you have to do is replace the redirect arrow with a pipe “|” and the Tee (or Tee-Object) command. This also works with other commands in PowerShell and is useful if you want to log and view console output at the same time.
Wrapping up
When it comes to troubleshooting a network or internet connection there are several possible ways to do it.
One of the simplest is to use the built-in Windows Ping utility to ping another computer because it can quickly help determine if there is a connection between the host and a remote computer.
Not only can the Ping command help you identify local network issues, but it can also be used to test the uptime of a remote IP address, server or website.
Ping does the job it’s designed for and is run from the command line or batch scripts, so you have to supply a few arguments to tailor it to your needs.
Although it’s powerful enough for most uses, one option missing from the Ping tool is the ability to include a time and date so you can see the exact point in time the ping response was received. That’s useful if you want to continuously ping over a period of time.
-
Windows Support Forums
-
Network and Internet
You should upgrade or use an alternative browser.
Ping with timestamp
-
Thread starter
Thread starterProgEngi
-
Start date
Start date
- Local time
- 12:27 PM
- Posts
- 109
- OS
- Windows 11
-
-
#1
Any help will be greatly appreciated
My Computer
-
- OS
- Windows 11
- Computer type
- Laptop
- Manufacturer/Model
- Various
- Local time
- 1:27 AM
- Posts
- 654
- OS
- Linux Mint
-
-
#2
@echo off
:loop
ping -n 1 8.8.8.8
echo %date% %time%
timeout /t 1 >null
goto loop
My Computer
-
- OS
- Linux Mint
- Computer type
- Laptop
- Manufacturer/Model
- System76 Lemur Pro
-
-
#3
My Computer
-
- OS
- Windows XP/7/8/8.1/10/11, Linux, Android, FreeBSD Unix
- Computer type
- Laptop
- Manufacturer/Model
- Dell XPS 15 9570
- CPU
- Intel® Core™ i7-8750H 8th Gen 2.2Ghz up to 4.1Ghz
- Motherboard
- Dell XPS 15 9570
- Memory
- 64GB using 2x32GB CL16 Mushkin redLine modules
- Graphics Card(s)
- Intel UHD 630 & NVIDIA GeForce GTX 1050 Ti with 4GB DDR5
- Sound Card
- Realtek ALC3266-CG
- Monitor(s) Displays
- 15.6″ 4K Touch UltraHD 3840×2160 made by Sharp
- Screen Resolution
- 3840×2160
- Hard Drives
- Toshiba KXG60ZNV1T02 NVMe 1TB SSD
- PSU
- Dell XPS 15 9570
- Case
- Dell XPS 15 9570
- Cooling
- Stock
- Keyboard
- Stock
- Mouse
- SwitftPoint ProPoint
- Internet Speed
- Comcast/XFinity 1.44Gbps/42.5Mbps
- Browser
- Microsoft EDGE (Chromium based) & Google Chrome
- Antivirus
- Windows Defender that came with Windows
- Local time
- 12:27 PM
- Posts
- 109
- OS
- Windows 11
-
-
#4
Ping has no timestamp of it’s own so something like this@echo off :loop ping -n 1 8.8.8.8 echo %date% %time% timeout /t 1 >null goto loop
I’m looking for cmd substitute of PowerShell that has output
My Computer
-
- OS
- Windows 11
- Computer type
- Laptop
- Manufacturer/Model
- Various
- Local time
- 12:27 PM
- Posts
- 109
- OS
- Windows 11
-
-
#5
Ping.exe 8.8.8.8 -t | ForEach {“{0} - {1}” -f (Get-Date),$_} > D:\Script1\Google.txt
How can it be forced to display as well?
My Computer
-
- OS
- Windows 11
- Computer type
- Laptop
- Manufacturer/Model
- Various
- Local time
- 1:27 AM
- Posts
- 654
- OS
- Linux Mint
-
-
#6
Ping.exe 8.8.8.8 -t | ForEach {“{0} - {1}” -f (Get-Date),$_} | Tee-Object -Append -FilePath D:\Script1\Google.txt
My Computer
-
- OS
- Linux Mint
- Computer type
- Laptop
- Manufacturer/Model
- System76 Lemur Pro
- Local time
- 12:27 PM
- Posts
- 109
- OS
- Windows 11
-
-
#7
Like thisPing.exe 8.8.8.8 -t | ForEach {“{0} - {1}” -f (Get-Date),$_} | Tee-Object -Append -FilePath D:\Script1\Google.txt
BRAVO neemobeer thanks a ZILLION
My Computer
-
- OS
- Windows 11
- Computer type
- Laptop
- Manufacturer/Model
- Various
- Local time
- 12:27 PM
- Posts
- 109
- OS
- Windows 11
-
-
#8
BRAVO neemobeer thanks a ZILLION
…however, needs little polishing to get
when stopped
My Computer
-
- OS
- Windows 11
- Computer type
- Laptop
- Manufacturer/Model
- Various
Similar threads
-
Windows Support Forums
-
Network and Internet
Sometimes you want to simply check something from a Windows system with ping and review it with timestamps. In order to do that you may use the following commands in powershell
ping.exe -t 8.8.4.4 |Foreach{«{0} — {1}» -f (Get-Date),$_} > C:\temp\ping_googledns1ipv4.txt
ping.exe -t 8.8.8.8 |Foreach{«{0} — {1}» -f (Get-Date),$_} > C:\temp\ping_googledns2ipv4.txt
ping.exe -t 2001:4860:4860::8844 |Foreach{«{0} — {1}» -f (Get-Date),$_} > C:\temp\ping_googledns1ipv4.txt
ping.exe -t 2001:4860:4860::8888 |Foreach{«{0} — {1}» -f (Get-Date),$_} > C:\temp\ping_googledns2ipv4.txt
Example without writing the output into a file:
PS C:\Users\flo>
PS C:\Users\flo> ping.exe -t 8.8.4.4 |Foreach{«{0} — {1}» -f (Get-Date),$_}
02.12.2020 08:53:32 —
02.12.2020 08:53:32 — Ping wird ausgeführt für 8.8.4.4 mit 32 Bytes Daten:
02.12.2020 08:53:32 — Antwort von 8.8.4.4: Bytes=32 Zeit=34ms TTL=56
02.12.2020 08:53:33 — Antwort von 8.8.4.4: Bytes=32 Zeit=42ms TTL=56
02.12.2020 08:53:34 — Antwort von 8.8.4.4: Bytes=32 Zeit=32ms TTL=56
02.12.2020 08:53:35 — Antwort von 8.8.4.4: Bytes=32 Zeit=34ms TTL=56
02.12.2020 08:53:36 — Antwort von 8.8.4.4: Bytes=32 Zeit=28ms TTL=56
02.12.2020 08:53:37 — Antwort von 8.8.4.4: Bytes=32 Zeit=31ms TTL=56
When network equipment is experiencing dropouts, you often need to run a constant ping to track when equipment or a connection may be failing.
There are several ways to do this, you could just run a ping command straight from Windows. Although, this approach does work and yes you can log pings in indefinitely with the “-t” switch – It does not timestamp your results.
Which makes it difficult in analyzing your results over a number of hours.
Ping with Timestamp on Windows
So, what are the solutions, well on Windows my preferred tool is HrPing – High-precision ping utility.
To get started with HrPing follow the below guide:
- Download HrPing from this link and once downloaded extract it to a folder.
- Open Command Prompt (Windows + R) then type CMD and click Ok.
- Once in command prompt navigate to the folder with your hrping.exe file.
- Then simply run a command like the below which logs a timestamp at the beginning of each line and sets a log file to look back on your results.
“hrping.exe google.com -t -T -F logfile-Google.txt”
Ping with Timestamp on Linux
Logging with Linux is simple, simply terminal into your Linux device or open up console if you’re already on a Linux machine.
The run the following command – Note there is no Verbrose output – But, you can open the text file the log is going into at any point until you cancel the command.
“sudo ping 192.168.1.101 | while read pong; do echo “$(date): $pong”; done > Ping-9pm.txt”
Note – I used sudo in my ping command as it’s pretty well the only way to execute commands on a Synology.