C как получить результаты ping
Перейти к содержимому

C как получить результаты ping

  • автор:

C# Ping

In this article we show how to determine the accessibility of a remote host in C# with the Ping class.

Ping is located in the System.Net.NetworkInformation namespace.

The name and the functionality of the Ping class come from the classic ping networking utility. The ping utility is used to test the reachability of a remote host on an IP network. It operates on the ICMP protocol.

The is used by hosts and routers to communicate network-layer information to each other. Typically, it is used for error reporting. The protocol is described by RFC 792.

Pinging is sending an ICMP echo request to the target host and waiting for an ICMP echo reply.

The Ping’s Send and SendAsync methods send an ICMP echo request message to a remote computer and wait for an ICMP echo reply message from that computer. The PingReply provides information about the status and data resulting from the message.

Advertisements C# Ping Send

The Send method sends the ICMP echo request message to a remote computer synchronously.

The program pings a remote host in a synchronous manner.

The Ping is located in the System.Net.NetworkInformation namespace.

A Ping object is created.

We ping a host specified by the URL and receive a PingReply .

We print the status code of the reply.

C# PingReply.RoundtripTime

The PingReply.RoundtripTime returns the number of milliseconds taken to send an ICMP echo request and receive the corresponding ICMP echo reply message.

The program sends three async ping requests and returns the status, address, and the round trip time.

The round trip time is retrieved through the RoundtripTime property of the PingReply .

Advertisements Ping Timeout

Some overloaded methods allow to specify a timeout option for the pinging.

We use the Linux traffic control utility to add a delay of 800 ms to the localhost.

This command removes all the rules for the lo interface.

In the program, we specify a timeout of 500 ms. We ping the localhost.

After adding the timeout rule with the traffic control utility, we have a timeout status.

After removing the delay rule, we receive success status.

C# ping example

In the next example, we create a program that accepts options for the number of packets and for a timeout.

The first argument, which is mandatory, is the url. The next two optional arguments are the number of packets and the timeout.

Пишем ping на Си

Видите это довольное лицо? Это Майк Муусс — автор, наверное самой часто используемой утилиты ping (недаром он на фотке так радуется).

Некоторое время назад мне самому довелось написать ping, но в виде отдельной функции.

И на мой взгляд, для си-программистов, которые только начинают работать с сетью, это очень полезная утилита для самостоятельной разработки. Почему? Потому, что для разработки этой утилиты нужно научится делать, казалось бы, самые примитивные действия — отправлять и принимать пакет.

Давайте сначала вкратце определим требования конкретно для нашей функции ping. Функция нужна нам для проверки целостности и качества соединения между хостами. И для этого нам достаточно отправить ICMP-эхопакет с запросом целевому хосту и получить от нее ответ. Для оценки качества соединения будем использовать время между запросом и получением ответа.

Системные вызовы

Операционная система (в нашем случае Linux) позволяет получать доступ к сетевым устройствам посредством системных вызовов. Для ping мне потребовались следующие вызовы:

  • socket — используется для создания сокета
  • select — в нашем случае используется для проверки состояния сокета
  • sendto — для отправки данных
  • recvfrom — для получения данных
  • inet_aton — для преобразования ip-aдреса в строковом виде в структуру sockaddr_in
  • и другие

Реализация

Функция для получения текущего времени

Для начала напишем вспомогательную функцию для получения текущего времени в миллисекундах.

Данные

Далее нужно определится с тем, какие данные будем отправлять. Объявим структуру, который будет иметь icmp заголовок и поле данных. Эта структура будет служить нашим пакетом.

Напишем функцию для заполнения нашей структуры.

Функция ping

Сигнатура нашей основной функции будет следующим.

На входе мы получаем ip-адрес пингуемого хоста и таймаут ожидания. На выходе результат выполнения и третий аргумент time куда запишем время пинга хоста.

Тут же, с помощью inet_aton , преобразуем ip в строковом виде в структуру sockaddr_in .

Сокет

Далее нам нужно создать сокет путем вызова соответствующей функции.

Директива SOCK_RAW говорит о том, что мы отправляем “сырой” пакет без использования транспортного уровня (UDP/TCP). С помощью директивы IPPROTO_ICMP говорим, что мы будем использовать протокол ICMP. Функция socket() возвращает нам файловый дескриптор, который будем использовать в последующем.

Отправляем пакет

Перед тем как отправить пакет фиксируем время.

И отправляем пакет.

Получаем ответ

Для получения ответа нужно считать принятые данные из сокета. Данные будут записаны в структуру ip_pkt .

Таймауты

Далее на мой взгляд идет самая сложная часть. Делать вызов recvfrom , то есть принимать данные из сети, нам нужно только при наличии данных. Для этого нам поможет системный вызов select , который используется для отслеживания состояния сокета. А именно:

  • Я взвожу select на требуемый таймаут, после чего происходит блокировка на этой функции до момента пока не появятся данные или не истечет время
  • Если select разблокировался по таймауту, значит время истекло и мы выходим из цикла
  • Если select разблокировался из-за появления данных, то вызываем recvfrom и записываем данные в структуру ip_pkt
  • Если данные адресованы не нам, взводим select заново, ведь у нас еще осталось время

Запуск

Компилируем, запускаем ping и видим, что все работает.

Стоп! Но почему для запуска требуется sudo? А потому, что мы используем сырые пакеты. Помните директиву SOCK_RAW ?

Тогда почему стандартная утилита ping не требует sudo? Ничего страшного. Пара нехитрых действий и наш ping тоже запускается без sudo.

Если есть вопросы или замечания — пишите! Я обязательно постараюсь ответить. Спасибо!

C как получить результаты ping

Prerequisites : ICMP | Raw Socket | Internet Checksum | DNS Ping is a necessity for debugging of the Internet. Ping is a basic Internet tool that allows a user to verify that a particular IP address exists and can accept requests., with other facilities. Ping sends out ICMP packets by opening a RAW socket, which is separate from TCP and UDP. Since IP does not have any inbuilt mechanism for sending error and control messages. It depends on Internet Control Message Protocol (ICMP) to provide an error control. It is used for reporting errors and management queries. Example of Ubuntu Ping

Working Mechanism The Internet Ping program works much like a sonar echo-location, sending a small packet of information containing an ICMP ECHO_REQUEST to a specified computer, which then sends an ECHO_REPLY packet in return. The packet has a TTL (time-to-live) value determining max number of router hops. If the packet does not reach, then the sender is noted back with the error. Errors are of following types:

  • TTL Expired in Transit
  • Destination Host Unreachable
  • Request Timed Out i.e. no reply
  • Unknown Host

Implementation The steps followed by a simple ping program are:

  1. Take a hostname as input
  2. Do a DNS lookup

DNS lookup can be done using gethostbyname(). The gethostbyname() function converts a normal human readable website and returns a structure of type hostent which contains IP address in form of binary dot notation and also address type.

How to run PING command and get ping host summary in C#?

I need to execute a PING command using C# code and get a summary of the ping host.

I need to send 8 packets, will display 8 echo replies in my command promt with statistics.

How to do it in C# console application?

Venkateswara Reddy's user avatar

3 Answers 3

Use this example:

If you need know about ping result here example:

Pal Bognar's user avatar

You can start a new Process with the cmd.exe x.x.x.x -n 8 as the file argument and the ping as the command argument.

Then, you can read its result data using a StreamReader which reads the process’ StandardOutput :

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *