Ping with timestamp windows

ping ping

Область применения: Windows Server (половина ежегодного канала), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 Applies to: Windows Server (Semi-Annual Channel), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012

Проверяет подключение на уровне IP к другому компьютеру TCP/IP, отправляя сообщения эхо-запросов протокола ICMP. Verifies IP-level connectivity to another TCP/IP computer by sending Internet Control Message Protocol (ICMP) echo Request messages. Отображаются сообщения о получении соответствующих эхо-ответов, а также время кругового пути. The receipt of corresponding echo Reply messages are displayed, along with round-trip times. Ping — это основная команда TCP/IP, используемая для устранения неполадок подключения, доступности и разрешения имен. ping is the primary TCP/IP command used to troubleshoot connectivity, reachability, and name resolution. При использовании без параметров эта команда отображает содержимое справки. Used without parameters, this command displays Help content.

Эту команду также можно использовать для проверки имени компьютера и IP-адреса компьютера. You can also use this command to test both the computer name and the IP address of the computer. Если проверка связи с IP-адресом выполнена успешно, но проверка связи с именем компьютера не выполняется, может возникнуть проблема разрешения имен. If pinging the IP address is successful, but pinging the computer name isn’t, you might have a name resolution problem. В этом случае убедитесь, что указываемое имя компьютера можно разрешить через локальный файл hosts с помощью запросов службы доменных имен (DNS) или методов разрешения имен NetBIOS. In this case, make sure the computer name you are specifying can be resolved through the local Hosts file, by using Domain Name System (DNS) queries, or through NetBIOS name resolution techniques.

Эта команда доступна, только если протокол Интернета (TCP/IP) установлен в качестве компонента в свойствах сетевого адаптера в окне Сетевые подключения. This command is available only if the Internet Protocol (TCP/IP) is installed as a component in the properties of a network adapter in Network Connections.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
/t /t Указывает, что команда ping Continue отправляет сообщения эхо-запросов в место назначения, пока не будет прервано. Specifies ping continue sending echo Request messages to the destination until interrupted. Чтобы прервать и отобразить статистику, нажмите клавиши CTRL + ВВОД. To interrupt and display statistics, press CTRL+ENTER. Чтобы прервать выполнение и выйти из этой команды, нажмите клавиши CTRL + C. To interrupt and quit this command, press CTRL+C.
/a /a Указывает, что разрешение имен должно выполняться на целевом IP-адресе. Specifies reverse name resolution be performed on the destination IP address. В случае успешного выполнения команды Ping отображает соответствующее имя узла. If this is successful, ping displays the corresponding host name.
параметра /n Указывает число сообщений запроса эха, которые будут отправлены. Specifies the number of echo Request messages be sent. Значение по умолчанию — 4. The default is 4.
/l /l Задает длину (в байтах) поля данных в сообщениях запроса эха. Specifies the length, in bytes, of the Data field in the echo Request messages. Значение по умолчанию — 32. The default is 32. Максимальный размер — 65 527. The maximum size is 65,527.
/f /f Указывает, что сообщения эхо-запросов отправляются с флагом «не фрагментировать » в заголовке IP, установленном в значение 1 (доступно только в IPv4). Specifies that echo Request messages are sent with the Do not Fragment flag in the IP header set to 1 (available on IPv4 only). Сообщения эхо-запроса не могут быть фрагментированы маршрутизаторами по пути к назначению. The echo Request message can’t be fragmented by routers in the path to the destination. Этот параметр полезен для устранения неполадок с максимальным количеством блоков передачи (PMTU). This parameter is useful for troubleshooting path Maximum Transmission Unit (PMTU) problems.
/I /I Задает значение поля срока жизни (TTL) в заголовке IP для отправленных сообщений эхо-запросов. Specifies the value of the Time To Live (TTL) field in the IP header for echo Request messages sent. По умолчанию используется значение TTL по умолчанию для узла. The default is the default TTL value for the host. Максимальный срок жизни — 255. The maximum TTL is 255.
/v /v Указывает значение поля типа службы (TOS) в IP-заголовке для отправленных сообщений запроса эха (доступно только в IPv4). Specifies the value of the Type Of Service (TOS) field in the IP header for echo Request messages sent (available on IPv4 only). Значение по умолчанию — 0. The default is 0. TOS задаются в виде десятичного значения от 0 до 255. TOS is specified as a decimal value from 0 through 255.
/r /r Указывает параметр записи маршрута в заголовке IP-адреса, который используется для записи пути, полученного сообщением запроса эха, и соответствующего сообщения о эхо-ответе (доступно только в IPv4). Specifies the Record Route option in the IP header is used to record the path taken by the echo Request message and corresponding echo Reply message (available on IPv4 only). Каждый прыжок в пути использует запись в параметре запись маршрута . Each hop in the path uses an entry in the Record Route option. Если это возможно, укажите значение счетчика , равное или больше, чем число прыжков между источником и назначением. If possible, specify a count equal to or greater than the number of hops between the source and destination. Число должно быть не меньше 1 и не больше 9. The count must be a minimum of 1 and a maximum of 9.
ключ /s Указывает, что параметр отметка времени Интернета в заголовке IP используется для записи времени прибытия сообщения эхо-запроса и соответствующего сообщения эхо-ответа для каждого прыжка. Specifies that the Internet timestamp option in the IP header is used to record the time of arrival for the echo Request message and corresponding echo Reply message for each hop. Число должно быть не меньше 1 и не больше 4. The count must be a minimum of 1 and a maximum of 4. Это необходимо для адресов назначения, находящейся в локальной связи. This is required for link-local destination addresses.
/j /j Указывает, что сообщения эхо-запроса используют параметр свободного исходного маршрута в заголовке IP с набором промежуточных назначений, указанных в hostlist (только в IPv4). Specifies the echo Request messages use the Loose Source Route option in the IP header with the set of intermediate destinations specified in hostlist (available on IPv4 only). При свободной маршрутизации последовательные промежуточные назначения могут быть разделены одним или несколькими маршрутизаторами. With loose source routing, successive intermediate destinations can be separated by one or multiple routers. Максимальное число адресов или имен в списке узлов равно 9. The maximum number of addresses or names in the host list is 9. Список узлов представляет собой набор IP-адресов (в точечно-десятичной нотации), разделенных пробелами. The host list is a series of IP addresses (in dotted decimal notation) separated by spaces.
/k /k Указывает, что сообщения эхо-запроса используют в заголовке IP параметр с максимальным исходным маршрутом с набором промежуточных назначений, указанных в hostlist (доступно только в IPv4). Specifies the echo Request messages use the Strict Source Route option in the IP header with the set of intermediate destinations specified in hostlist (available on IPv4 only). При использовании явной исходной маршрутизации следующее промежуточное назначение должно быть напрямую достижимо (оно должно быть соседом в интерфейсе маршрутизатора). With strict source routing, the next intermediate destination must be directly reachable (it must be a neighbor on an interface of the router). Максимальное число адресов или имен в списке узлов равно 9. The maximum number of addresses or names in the host list is 9. Список узлов представляет собой набор IP-адресов (в точечно-десятичной нотации), разделенных пробелами. The host list is a series of IP addresses (in dotted decimal notation) separated by spaces.
/w /w Указывает время ожидания сообщения эхо-ответа, соответствующего заданному сообщению запроса эха, в миллисекундах. Specifies the amount of time, in milliseconds, to wait for the echo Reply message corresponding to a given echo Request message. Если ответное сообщение не получено в течение времени ожидания, отображается сообщение об ошибке «запрос был превышен). If the echo Reply message is not received within the time-out, the «Request timed out» error message is displayed. Время ожидания по умолчанию — 4000 (4 секунды). The default time-out is 4000 (4 seconds).
/R /R Указывает путь к пути приема-передачи, который отслеживается (доступно только в IPv6). Specifies the round-trip path is traced (available on IPv6 only).
Ключ /S Указывает используемый исходный адрес (доступен только в IPv6). Specifies the source address to use (available on IPv6 only).
/4 /4 Указывает IPv4, используемый для проверки связи. Specifies IPv4 used to ping. Этот параметр не требуется для определения целевого узла с IPv4-адресом. This parameter is not required to identify the target host with an IPv4 address. Необходимо только указать целевой узел по имени. It is only required to identify the target host by name.
/6 /6 Указывает IPv6, используемый для проверки связи. Specifies IPv6 used to ping. Этот параметр не требуется для определения целевого узла с IPv6-адресом. This parameter is not required to identify the target host with an IPv6 address. Необходимо только указать целевой узел по имени. It is only required to identify the target host by name.
Указывает имя узла или IP-адрес назначения. Specifies the host name or IP address of the destination.
/? /? Отображение справки в командной строке. Displays help at the command prompt.

Пример выходных данных команды ping Example of the ping command output

Примеры Examples

Чтобы проверить связь с целевым 10.0.99.221 и разрешить 10.0.99.221 в его имя узла, введите: To ping the destination 10.0.99.221 and resolve 10.0.99.221 to its host name, type:

Чтобы проверить связь с 10.0.99.221 назначения с 10 сообщениями эхо-запроса, каждый из которых имеет поле данных 1000 байт, введите: To ping the destination 10.0.99.221 with 10 echo Request messages, each of which has a Data field of 1000 bytes, type:

Чтобы проверить связь с назначением 10.0.99.221 и записать маршрут для 4 прыжков, введите: To ping the destination 10.0.99.221 and record the route for 4 hops, type:

Чтобы проверить связь с целевым 10.0.99.221 и указать свободный исходный маршрут 10.12.0.1-10.29.3.1-10.1.44.1, введите: To ping the destination 10.0.99.221 and specify the loose source route of 10.12.0.1-10.29.3.1-10.1.44.1, type:

Ping with timestamp on Windows CLI

On the Windows command prompt cmd , I use ping -t to 10.21.11.81

Are there any possibilities to get an output like this?

Please note that I wanna achieve this with only commands provided by CMD

16 Answers 16

note: code to be used inside a batch file. To use from command line replace %%a with %a

Start the ping, force a correct line buffered output ( find /v ), and start a cmd process with delayed expansion enabled that will do an infinite loop reading the piped data that will be echoed to console prefixed with the current time.

2015-01-08 edited: In faster/newer machines/os versions there is a synchronization problem in previous code, making the set /p read a line while the ping command is still writting it and the result are line cuts.

Two aditional pause commands are included at the start of the subshell (only one can be used, but as pause consumes a input character, a CRLF pair is broken and a line with a LF is readed) to wait for input data, and a ping -n 2 localhost is included to wait a second for each read in the inner loop. The result is a more stable behaviour and less CPU usage.

NOTE: The inner ping can be replaced with a pause , but then the first character of each readed line is consumed by the pause and not retrieved by the set /p

7 Ways to Timestamp Ping Results

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.

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.

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.

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.

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.

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.

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.

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.

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.

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 @>,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.

Читайте также:  Windows product policy editor
Оцените статью