Меню Рубрики

Ping в проекте windows forms

Ping Класс

Определение

Позволяет приложению определить, доступен ли удаленный компьютер по сети. Allows an application to determine whether a remote computer is accessible over the network.

Примеры

В следующем примере кода показано использование Ping класса в синхронном режиме. The following code example demonstrates using the Ping class synchronously.

В следующем примере кода показано использование Ping класса в асинхронном режиме. The following code example demonstrates using the Ping class asynchronously.

Комментарии

Приложения используют Ping класс, чтобы определить, доступен ли удаленный компьютер. Applications use the Ping class to detect whether a remote computer is reachable.

Топология сети может определить Ping , может ли служба успешно связаться с удаленным узлом. Network topology can determine whether Ping can successfully contact a remote host. Присутствие и настройка прокси-серверов, оборудования преобразования сетевых адресов (NAT) или брандмауэров может помешать Ping выполнению. The presence and configuration of proxies, network address translation (NAT) equipment, or firewalls can prevent Ping from succeeding. Успешная проверка Ping означает, что удаленный узел доступен только в сети; наличие служб более высокого уровня (например, веб-сервера) на удаленном узле не гарантируется. A successful Ping indicates only that the remote host can be reached on the network; the presence of higher level services (such as a Web server) on the remote host is not guaranteed.

Этот класс предоставляет функциональные возможности, аналогичные средству командной строки Ping.exe. This class provides functionality similar to the Ping.exe command line tool. SendМетоды и SendAsync отправляют на удаленный компьютер сообщение с эхо-запросом протокола ICMP и ожидают ответа ICMP эхо от этого компьютера. The Send and SendAsync methods send an Internet Control Message Protocol (ICMP) echo request message to a remote computer and waits for an ICMP echo reply message from that computer. Подробное описание ICMP-сообщений см. в документе RFC 792, доступном по адресу https://www.ietf.org . For a detailed description of ICMP messages, see RFC 792, available at https://www.ietf.org.

Следующие типы используются с Ping классом и подробно описаны ниже. The following types are used with the Ping class and are described in detail below.

Имя типа Type name Описание Description
IPStatus Определяет коды состояния, описывающие результат сообщения запроса проверки связи ICMP. Defines status codes that describe the outcome of an ICMP echo request message.
PingOptions Позволяет настраивать или извлекать параметры, управляющие количеством перенаправляемых пакетов запросов ( Ttl ) и возможностью его фрагментации ( DontFragment ). Allows you to configure or retrieve the settings that control how many times the request packet can be forwarded (Ttl), and whether it can be fragmented (DontFragment ).
PingReply Содержит результаты запроса проверки связи ICMP. Contains the results of an ICMP echo request.
PingException Возникает при неустранимой ошибке. Thrown if an unrecoverable error occurs.
PingCompletedEventArgs Содержит данные, связанные с PingCompleted событиями, которые вызываются, когда SendAsync вызов завершается или отменяется. Contains the data associated with PingCompleted events, which are raised when a SendAsync call completes or is canceled.
PingCompletedEventHandler Делегат, предоставляющий метод обратного вызова, вызываемый при SendAsync завершении или отмене вызова. The delegate that provides the callback method invoked when a SendAsync call completes or is canceled.

SendМетоды и SendAsync возвращают ответ в PingReply объекте. The Send and SendAsync methods return the reply in a PingReply object. PingReply.StatusСвойство возвращает значение, IPStatus указывающее результат запроса. The PingReply.Status property returns an IPStatus value to indicate the outcome of the request.

При отправке запроса необходимо указать удаленный компьютер. When sending the request, you must specify the remote computer. Это можно сделать, указав строку имени узла, IP-адрес в строковом формате или IPAddress объект. You can do this by providing a host name string, an IP address in string format, or an IPAddress object.

Можно также указать любой из следующих типов сведений: You can also specify any of the following types of information:

Данные, сопровождающие запрос. Data to accompany the request. Указание buffer позволяет узнать количество времени, требуемое для передачи пакета определенного размера на удаленный узел и от него до максимальной пересылки сетевого пути. Specifying buffer allows you to learn the amount of time required for a packet of a particular size to travel to and from the remote host and the maximum transmission unit of the network path. (См Send SendAsync . перегрузки или, которые принимают buffer параметр.) (See the Send or SendAsync overloads that take a buffer parameter.)

Можно ли фрагментировать эхо-пакет ICMP при передаче. Whether the ICMP Echo packet can be fragmented in transit. (См DontFragment . свойство и Send SendAsync перегрузки, которые принимают options параметр.) (See the DontFragment property and the Send or SendAsync overloads that take an options parameter.)

Сколько раз узлы маршрутизации, такие как маршрутизаторы или шлюзы, могут переслать пакет до того, как он достигнет конечного компьютера или отклоняется. How many times routing nodes, such as routers or gateways, can forward the packet before it either reaches the destination computer or is discarded. (См Ttl ., а также Send SendAsync перегрузки, принимающие options параметр.) (See Ttl and the Send or SendAsync overloads that take an options parameter.)

Предельное время, в течение которого должен быть получен ответ. The time limit within which the reply must be received. (См Send SendAsync . перегрузки или, которые принимают timeout параметр. (See the Send or SendAsync overloads that take a timeout parameter.

PingКласс предлагает как синхронные, так и асинхронные методы для отправки запроса. The Ping class offers both synchronous and asynchronous methods for sending the request. Если приложение должно блокироваться во время ожидания ответа, используйте методы. Send эти методы являются синхронными. If your application should block while waiting for a reply, use the Send methods; these methods are synchronous. Если приложение не должно блокироваться, используйте асинхронные SendAsync методы. If your application should not block, use the asynchronous SendAsync methods. Вызов метода SendAsync выполняется в собственном потоке, который автоматически выделяется из пула потоков. A call to SendAsync executes in its own thread that is automatically allocated from the thread pool. По завершении асинхронной операции она вызывает PingCompleted событие. When the asynchronous operation completes, it raises the PingCompleted event. Приложения используют PingCompletedEventHandler делегат, чтобы указать метод, который вызывается для PingCompleted событий. Applications use a PingCompletedEventHandler delegate to specify the method that is called for PingCompleted events. PingCompletedEventHandlerПеред вызовом необходимо добавить делегат к событию SendAsync . You must add a PingCompletedEventHandler delegate to the event before calling SendAsync. Метод делегата получает PingCompletedEventArgs объект, содержащий PingReply объект, описывающий результат SendAsync вызова. The delegate’s method receives a PingCompletedEventArgs object that contains a PingReply object that describes the result of the SendAsync call.

Нельзя использовать один и тот же экземпляр Ping класса для создания нескольких одновременных эхо-запросов ICMP. You cannot use the same instance of the Ping class to generate multiple simultaneous ICMP Echo requests. Вызов Send во время SendAsync выполнения вызова или несколько раз при вызове метода SendAsync до завершения всех предыдущих вызовов приводит к возникновению исключения InvalidOperationException . Calling Send while a SendAsync call is in progress or calling SendAsync multiple times before all previous calls have completed causes an InvalidOperationException.

Конструкторы

Инициализирует новый экземпляр класса Ping. Initializes a new instance of the Ping class.

Свойства

Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.

Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.

Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.

Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.

Методы

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

Освобождает неуправляемые ресурсы и удаляет управляемые ресурсы, используемые объектом Ping. Releases the unmanaged resources and disposes of the managed resources used by the Ping.

Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.

Освобождает неуправляемые ресурсы, используемые объектом Ping, и опционально — управляемые ресурсы. Releases the unmanaged resources used by the Ping object, and optionally disposes of the managed resources.

Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the Component and optionally releases the managed resources.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

Служит в качестве хэш-функции по умолчанию. Serves as the default hash function.

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.

Вызывает событие PingCompleted. Raises the PingCompleted event.

Предпринимает попытку отправки сообщения запроса проверки связи ICMP на удаленный компьютер с указанным IPAddress и получения от него соответствующего сообщения ответа проверки связи ICMP. Attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified IPAddress, and receive a corresponding ICMP echo reply message from that computer.

Предпринимает попытку отправки сообщения запроса проверки связи ICMP с заданным буфером данных на удаленный компьютер с указанным IPAddress и получения от него соответствующего сообщения ответа проверки связи ICMP. Attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receive a corresponding ICMP echo reply message from that computer. Этот метод позволяет указать тайм-аут операции. This method allows you to specify a time-out value for the operation.

Предпринимает попытку отправки сообщения запроса проверки связи ICMP с заданным буфером данных на удаленный компьютер с указанным IPAddress и получения от него соответствующего сообщения ответа проверки связи ICMP. Attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции. This overload allows you to specify a time-out value for the operation.

Предпринимает попытку отправки сообщения запроса проверки связи ICMP с заданным буфером данных на удаленный компьютер с указанным IPAddress и получения от него соответствующего сообщения ответа проверки связи ICMP. Attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции и управлять значениями фрагментации и срока жизни пакета сообщения проверки связи ICMP. This overload allows you to specify a time-out value for the operation and control fragmentation and Time-to-Live values for the ICMP echo message packet.

Предпринимает попытку отправки сообщения запроса проверки связи ICMP на указанный компьютер и получения от него соответствующего сообщения ответа проверки связи ICMP. Attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer, and receive a corresponding ICMP echo reply message from that computer.

Предпринимает попытку отправки сообщения запроса проверки связи ICMP на указанный компьютер и получения от него соответствующего сообщения ответа проверки связи ICMP. Attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer, and receive a corresponding ICMP echo reply message from that computer. Этот метод позволяет указать тайм-аут операции. This method allows you to specify a time-out value for the operation.

Предпринимает попытку отправки сообщения запроса проверки связи ICMP с заданным буфером данных на указанный компьютер и получения от него соответствующего сообщения ответа проверки связи ICMP. Attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции. This overload allows you to specify a time-out value for the operation.

Предпринимает попытку отправки сообщения запроса проверки связи ICMP с заданным буфером данных на указанный компьютер и получения от него соответствующего сообщения ответа проверки связи ICMP. Attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции и управлять значениями фрагментации и срока жизни пакета ICMP. This overload allows you to specify a time-out value for the operation and control fragmentation and Time-to-Live values for the ICMP packet.

Предпринимает попытку асинхронной отправки сообщения запроса проверки связи ICMP с заданным буфером данных на компьютер с указанным IPAddress и получения от него соответствующего сообщения ответа проверки связи ICMP. Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции. This overload allows you to specify a time-out value for the operation.

Предпринимает попытку асинхронной отправки сообщения запроса проверки связи ICMP с заданным буфером данных на компьютер с указанным IPAddress и получения от него соответствующего сообщения ответа проверки связи ICMP. Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции и управлять значениями фрагментации и срока жизни пакета сообщения проверки связи ICMP. This overload allows you to specify a time-out value for the operation and control fragmentation and Time-to-Live values for the ICMP echo message packet.

Предпринимает попытку асинхронной отправки сообщения запроса проверки связи ICMP на удаленный компьютер с указанным IPAddress и получения от него соответствующего сообщения ответа проверки связи ICMP. Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified IPAddress, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции. This overload allows you to specify a time-out value for the operation.

Предпринимает попытку асинхронной отправки сообщения запроса проверки связи ICMP на удаленный компьютер с указанным IPAddress и получения от него соответствующего сообщения ответа проверки связи ICMP. Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified IPAddress, and receive a corresponding ICMP echo reply message from that computer.

Предпринимает попытку асинхронной отправки сообщения запроса проверки связи ICMP с заданным буфером данных на указанный компьютер и получения от него соответствующего сообщения ответа проверки связи ICMP. Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции. This overload allows you to specify a time-out value for the operation.

Предпринимает попытку асинхронной отправки сообщения запроса проверки связи ICMP с заданным буфером данных на указанный компьютер и получения от него соответствующего сообщения ответа проверки связи ICMP. Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции и управлять значениями фрагментации и срока жизни пакета ICMP. This overload allows you to specify a time-out value for the operation and control fragmentation and Time-to-Live values for the ICMP packet.

Предпринимает попытку асинхронной отправки сообщения запроса проверки связи ICMP на указанный компьютер и получения от него соответствующего сообщения ответа проверки связи ICMP. Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer, and receive a corresponding ICMP echo reply message from that computer. Эта перегруженная версия метода позволяет указать тайм-аут операции. This overload allows you to specify a time-out value for the operation.

Предпринимает попытку асинхронной отправки сообщения запроса проверки связи ICMP на указанный компьютер и получения от него соответствующего сообщения ответа проверки связи ICMP. Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer, and receive a corresponding ICMP echo reply message from that computer.

Отменяет все ожидающие асинхронные запросы на отправку сообщений проверки связи ICMP и получает соответствующее сообщение ответа проверки связи ICMP. Cancels all pending asynchronous requests to send an Internet Control Message Protocol (ICMP) echo message and receives a corresponding ICMP echo reply message.

Отправляет сообщение запроса проверки связи ICMP с заданным буфером данных на компьютер с указанным IPAddress и получает от него соответствующее сообщения ответа проверки связи ICMP как асинхронная операция. Send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receives a corresponding ICMP echo reply message from that computer as an asynchronous operation.

Отправляет сообщение запроса проверки связи ICMP с заданным буфером данных на компьютер с указанным IPAddress и получает от него соответствующее сообщения ответа проверки связи ICMP как асинхронная операция. Send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receives a corresponding ICMP echo reply message from that computer as an asynchronous operation. Эта перегруженная версия метода позволяет указать тайм-аут операции. This overload allows you to specify a time-out value for the operation.

Отправляет сообщение запроса проверки связи ICMP с заданным буфером данных на компьютер с указанным IPAddress и получает от него соответствующее сообщения ответа проверки связи ICMP как асинхронная операция. Send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receives a corresponding ICMP echo reply message from that computer as an asynchronous operation. Эта перегрузка позволяет указать значение истечения времени ожидания для операции и буфер для использования для отправки и получения. This overload allows you to specify a time-out value for the operation and a buffer to use for send and receive.

Отправляет сообщение запроса проверки связи ICMP с заданным буфером данных на компьютер с указанным IPAddress и получает от него соответствующее сообщение ответа проверки связи ICMP в виде асинхронной операции. Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receives a corresponding ICMP echo reply message from that computer as an asynchronous operation. Эта перегруженная версия метода позволяет указать тайм-аут операции, буфер для использования для отправки и получения и управлять значениями фрагментации и срока жизни пакета сообщения проверки связи ICMP. This overload allows you to specify a time-out value for the operation, a buffer to use for send and receive, and control fragmentation and Time-to-Live values for the ICMP echo message packet.

Отправляет сообщение запроса проверки связи ICMP с заданным буфером данных на указанный компьютер и получает от него соответствующее сообщения ответа проверки связи ICMP как асинхронная операция. Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and receive a corresponding ICMP echo reply message from that computer as an asynchronous operation.

Отправляет сообщение запроса проверки связи ICMP с заданным буфером данных на указанный компьютер и получает от него соответствующее сообщения ответа проверки связи ICMP как асинхронная операция. Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and receive a corresponding ICMP echo reply message from that computer as an asynchronous operation. Эта перегруженная версия метода позволяет указать тайм-аут операции. This overload allows you to specify a time-out value for the operation.

Отправляет сообщение запроса проверки связи ICMP с заданным буфером данных на указанный компьютер и получает от него соответствующее сообщения ответа проверки связи ICMP как асинхронная операция. Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and receive a corresponding ICMP echo reply message from that computer as an asynchronous operation. Эта перегрузка позволяет указать значение истечения времени ожидания для операции и буфер для использования для отправки и получения. This overload allows you to specify a time-out value for the operation and a buffer to use for send and receive.

Отправляет сообщение запроса проверки связи ICMP с заданным буфером данных на указанный компьютер и получает от него соответствующее сообщения ответа проверки связи ICMP как асинхронная операция. Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and receive a corresponding ICMP echo reply message from that computer as an asynchronous operation. Эта перегруженная версия метода позволяет указать тайм-аут операции, буфер для использования для отправки и получения и управлять значениями фрагментации и срока жизни пакета сообщения проверки связи ICMP. This overload allows you to specify a time-out value for the operation, a buffer to use for send and receive, and control fragmentation and Time-to-Live values for the ICMP echo message packet.

Возвращает объект String, содержащий имя Component, если оно есть. Returns a String containing the name of the Component, if any. Этот метод не следует переопределять. This method should not be overridden.

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

События

Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.

Происходит при завершении или отмене асинхронной операции отправки сообщения проверки связи ICMP и получения соответствующего сообщения ответа проверки связи ICMP. Occurs when an asynchronous operation to send an Internet Control Message Protocol (ICMP) echo message and receive the corresponding ICMP echo reply message completes or is canceled.

Явные реализации интерфейса

Освобождает все ресурсы, используемые экземплярами класса Ping. Releases all resources used by instances of the Ping class.

Источник

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

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

  • Ping windows размер пакета
  • Ping windows with port
  • Ping scanner windows 7
  • Ping monitor gadget windows 7
  • Ping cmd windows 7