.NET Framework Class Library Ping Class Allows an application to determine whether a remote computer is accessible over the network.

Inheritance Hierarchy
Namespace:
System.Net.NetworkInformation
Assembly:
System (in System.dll)

Syntax
Public Class Ping _
Inherits Component
public class Ping : Component
public ref class Ping : public Component
type Ping =
class
inherit Component
end
The Ping type exposes the following members.

Constructors
|
| Name | Description |
|---|
.gif) | Ping | Initializes a new instance of the Ping class. | Top

Properties

Methods
|
| Name | Description |
|---|
.gif) | CreateObjRef | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) | .gif) | Dispose()()() | Releases all resources used by the Component. (Inherited from Component.) | .gif) | Dispose(Boolean) | Releases the unmanaged resources used by the Ping object, and optionally disposes of the managed resources. (Overrides Component..::.Dispose(Boolean).) | .gif) | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | .gif) | Finalize | Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.) | .gif) | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | .gif) | GetLifetimeService | Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) | .gif) | GetService | Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.) | .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) | InitializeLifetimeService | Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) | .gif) | MemberwiseClone()()() | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) | MemberwiseClone(Boolean) | Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) | .gif) | OnPingCompleted | Raises the PingCompleted event. | .gif) | Send(IPAddress) | 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. | .gif) | Send(String) | 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. | .gif) | Send(IPAddress, Int32) | 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. | .gif) | Send(String, Int32) | 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. | .gif) | Send(IPAddress, Int32, array<Byte>[]()[]) | 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. | .gif) | Send(String, Int32, array<Byte>[]()[]) | 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. | .gif) | Send(IPAddress, Int32, array<Byte>[]()[], PingOptions) | 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 and control fragmentation and Time-to-Live values for the ICMP echo message packet. | .gif) | Send(String, Int32, array<Byte>[]()[], PingOptions) | 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 and control fragmentation and Time-to-Live values for the ICMP packet. | .gif) | SendAsync(IPAddress, Object) | 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. | .gif) | SendAsync(String, Object) | 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. | .gif) | SendAsync(IPAddress, Int32, Object) | 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. | .gif) | SendAsync(String, Int32, Object) | 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. | .gif) | SendAsync(IPAddress, Int32, array<Byte>[]()[], Object) | 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. | .gif) | SendAsync(String, Int32, array<Byte>[]()[], Object) | 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. | .gif) | SendAsync(IPAddress, Int32, array<Byte>[]()[], PingOptions, Object) | 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 and control fragmentation and Time-to-Live values for the ICMP echo message packet. | .gif) | SendAsync(String, Int32, array<Byte>[]()[], PingOptions, Object) | 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 and control fragmentation and Time-to-Live values for the ICMP packet. | .gif) | SendAsyncCancel | Cancels all pending asynchronous requests to send an Internet Control Message Protocol (ICMP) echo message and receives a corresponding ICMP echo reply message. | .gif) | ToString | Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.) | Top

Remarks
Applications use the Ping class to detect whether a remote computer is reachable. Network topology can determine whether Ping can successfully contact a remote host. The presence and configuration of proxies, network address translation (NAT) equipment, or firewalls can prevent Ping from succeeding. 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. This class provides functionality similar to the Ping.exe command line tool. 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. For a detailed description of ICMP messages, see RFC 792, available at http://www.ietf.org. The following types are used with the Ping class and are described in detail below.
Type name
|
Description
|
|---|
IPStatus
| Defines status codes that describe the outcome of an ICMP echo request message. |
PingOptions
| 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
| Contains the results of an ICMP echo request. |
PingException
| Thrown if an unrecoverable error occurs. |
PingCompletedEventArgs
| Contains the data associated with PingCompleted events, which are raised when a SendAsync call completes or is canceled. |
PingCompletedEventHandler | The delegate that provides the callback method invoked when a SendAsync call completes or is canceled. |
The Send and SendAsync methods return the reply in a PingReply object. 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. 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. 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. (See the Send or SendAsync overloads that take a buffer parameter.) Whether the ICMP Echo packet can be fragmented in transit. (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. (See Ttl and the Send or SendAsync overloads that take an options parameter.) The time limit within which the reply must be received. (See the Send or SendAsync overloads that take a timeout parameter.
The Ping class offers both synchronous and asynchronous methods for sending the request. If your application should block while waiting for a reply, use the Send methods; these methods are synchronous. If your application should not block, use the asynchronous SendAsync methods. A call to SendAsync executes in its own thread that is automatically allocated from the thread pool. When the asynchronous operation completes, it raises the PingCompleted event. Applications use a PingCompletedEventHandler delegate to specify the method that is called for PingCompleted events. You must add a PingCompletedEventHandler delegate to the event before calling SendAsync. The delegate's method receives a PingCompletedEventArgs object that contains a PingReply object that describes the result of the SendAsync call. You cannot use the same instance of the Ping class to generate multiple simultaneous ICMP Echo requests. Calling Send while a SendAsync call is in progress or calling SendAsync multiple times before all previous calls have completed causes an InvalidOperationException.

Examples
The following code example demonstrates using the Ping class synchronously.
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
// args[0] can be an IPaddress or host name.
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::Net::NetworkInformation;
using namespace System::Text;
// args[1] can be an IPaddress or host name.
int main()
{
array<String^>^args = Environment::GetCommandLineArgs();
Ping ^ pingSender = gcnew Ping;
PingOptions ^ options = gcnew PingOptions;
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options->DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
String^ data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
array<Byte>^buffer = Encoding::ASCII->GetBytes( data );
int timeout = 120;
PingReply ^ reply = pingSender->Send( args[ 1 ], timeout, buffer, options );
if ( reply->Status == IPStatus::Success )
{
Console::WriteLine( "Address: {0}", reply->Address->ToString() );
Console::WriteLine( "RoundTrip time: {0}", reply->RoundtripTime );
Console::WriteLine( "Time to live: {0}", reply->Options->Ttl );
Console::WriteLine( "Don't fragment: {0}", reply->Options->DontFragment );
Console::WriteLine( "Buffer size: {0}", reply->Buffer->Length );
}
}
The following code example demonstrates using the Ping class asynchronously.
using System;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Threading;
namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
public static void Main (string[] args)
{
if (args.Length == 0)
throw new ArgumentException ("Ping needs a host or IP Address.");
string who = args[0];
AutoResetEvent waiter = new AutoResetEvent (false);
Ping pingSender = new Ping ();
// When the PingCompleted event is raised,
// the PingCompletedCallback method is called.
pingSender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
// Wait 12 seconds for a reply.
int timeout = 12000;
// Set options for transmission:
// The data can go through 64 gateways or routers
// before it is destroyed, and the data packet
// cannot be fragmented.
PingOptions options = new PingOptions (64, true);
Console.WriteLine ("Time to live: {0}", options.Ttl);
Console.WriteLine ("Don't fragment: {0}", options.DontFragment);
// Send the ping asynchronously.
// Use the waiter as the user token.
// When the callback completes, it can wake up this thread.
pingSender.SendAsync(who, timeout, buffer, options, waiter);
// Prevent this example application from ending.
// A real application should do something useful
// when possible.
waiter.WaitOne ();
Console.WriteLine ("Ping example completed.");
}
private static void PingCompletedCallback (object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
Console.WriteLine ("Ping canceled.");
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
((AutoResetEvent)e.UserState).Set ();
}
// If an error occurred, display the exception to the user.
if (e.Error != null)
{
Console.WriteLine ("Ping failed:");
Console.WriteLine (e.Error.ToString ());
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
PingReply reply = e.Reply;
DisplayReply (reply);
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
public static void DisplayReply (PingReply reply)
{
if (reply == null)
return;
Console.WriteLine ("ping status: {0}", reply.Status);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}
#using <System.dll>
using namespace System;
using namespace System::Text;
using namespace System::Net;
using namespace System::Net::NetworkInformation;
using namespace System::ComponentModel;
using namespace System::Threading;
void PingCompletedCallback( Object^ sender, PingCompletedEventArgs^ e );
void DisplayReply( PingReply^ reply );
int main()
{
array<String^>^args = Environment::GetCommandLineArgs();
if ( args->Length == 1 )
throw gcnew ArgumentException( "Ping needs a host or IP Address." );
String^ who = args[ 1 ];
AutoResetEvent^ waiter = gcnew AutoResetEvent( false );
Ping ^ pingSender = gcnew Ping;
// When the PingCompleted event is raised,
// the PingCompletedCallback method is called.
pingSender->PingCompleted += gcnew PingCompletedEventHandler( PingCompletedCallback );
// Create a buffer of 32 bytes of data to be transmitted.
String^ data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
array<Byte>^buffer = Encoding::ASCII->GetBytes( data );
// Wait 12 seconds for a reply.
int timeout = 12000;
// Set options for transmission:
// The data can go through 64 gateways or routers
// before it is destroyed, and the data packet
// cannot be fragmented.
PingOptions ^ options = gcnew PingOptions( 64,true );
Console::WriteLine( "Time to live: {0}", options->Ttl );
Console::WriteLine( "Don't fragment: {0}", options->DontFragment );
// Send the ping asynchronously.
// Use the waiter as the user token.
// When the callback completes, it can wake up this thread.
pingSender->SendAsync( who, timeout, buffer, options, waiter );
// Prevent this example application from ending.
// A real application should do something useful
// when possible.
waiter->WaitOne();
Console::WriteLine( "Ping example completed." );
}
void PingCompletedCallback( Object^ /*sender*/, PingCompletedEventArgs^ e )
{
// If the operation was canceled, display a message to the user.
if ( e->Cancelled )
{
Console::WriteLine( "Ping canceled." );
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
(dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
}
// If an error occurred, display the exception to the user.
if ( e->Error != nullptr )
{
Console::WriteLine( "Ping failed:" );
Console::WriteLine( e->Error->ToString() );
// Let the main thread resume.
(dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
}
PingReply ^ reply = e->Reply;
DisplayReply( reply );
// Let the main thread resume.
(dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
}
void DisplayReply( PingReply ^ reply )
{
if ( reply == nullptr )
return;
Console::WriteLine( "ping status: {0}", reply->Status );
if ( reply->Status == IPStatus::Success )
{
Console::WriteLine( "Address: {0}", reply->Address->ToString() );
Console::WriteLine( "RoundTrip time: {0}", reply->RoundtripTime );
Console::WriteLine( "Time to live: {0}", reply->Options->Ttl );
Console::WriteLine( "Don't fragment: {0}", reply->Options->DontFragment );
Console::WriteLine( "Buffer size: {0}", reply->Buffer->Length );
}
}

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Biblioteca de clases de .NET Framework Ping (Clase) Permite que una aplicación determine si un equipo remoto está accesible a través de la red.

Jerarquía de herencia
Espacio de nombres:
System.Net.NetworkInformation
Ensamblado:
System (en System.dll)

Sintaxis
Public Class Ping _
Inherits Component
public class Ping : Component
public ref class Ping : public Component
type Ping =
class
inherit Component
end
El tipo Ping expone los siguientes miembros.

Constructores
|
| Nombre | Descripción |
|---|
.gif) | Ping | Inicializa una nueva instancia de la clase Ping. | Arriba

Propiedades

Métodos
|
| Nombre | Descripción |
|---|
.gif) | CreateObjRef | Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto. (Se hereda de MarshalByRefObject). | .gif) | Dispose()()() | Libera todos los recursos utilizados por el objeto Component. (Se hereda de Component). | .gif) | Dispose(Boolean) | Libera los recursos no administrados que utiliza el objeto Ping y, de forma opcional, desecha los recursos administrados. (Invalida a Component..::.Dispose(Boolean)). | .gif) | Equals(Object) | Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object). | .gif) | Finalize | Libera recursos no administrados y realiza otras operaciones de limpieza antes de que se reclame el objeto Component durante la recolección de elementos no utilizados. (Se hereda de Component). | .gif) | GetHashCode | Actúa como función hash para un tipo concreto. (Se hereda de Object). | .gif) | GetLifetimeService | Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject). | .gif) | GetService | Devuelve un objeto que representa el servicio suministrado por Component o por Container. (Se hereda de Component). | .gif) | GetType | Obtiene el objeto Type de la instancia actual. (Se hereda de Object). | .gif) | InitializeLifetimeService | Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject). | .gif) | MemberwiseClone()()() | Crea una copia superficial del objeto Object actual. (Se hereda de Object). | .gif) | MemberwiseClone(Boolean) | Crea una copia superficial del objeto MarshalByRefObject actual. (Se hereda de MarshalByRefObject). | .gif) | OnPingCompleted | Provoca el evento PingCompleted. | .gif) | Send(IPAddress) | Intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) al equipo que tiene la IPAddress especificada y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. | .gif) | Send(String) | Intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) al equipo especificado y recibir un mensaje de respuesta de eco ICMP correspondiente de dicho equipo. | .gif) | Send(IPAddress, Int32) | Intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo que tiene la IPAddress especificada y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. Este método permite especificar un valor de tiempo de espera para la operación. | .gif) | Send(String, Int32) | Intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) al equipo especificado y recibir un mensaje de respuesta de eco ICMP correspondiente de dicho equipo. Este método permite especificar un valor de tiempo de espera para la operación. | .gif) | Send(IPAddress, Int32, array<Byte>[]()[]) | Intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo que tiene la IPAddress especificada y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación. | .gif) | Send(String, Int32, array<Byte>[]()[]) | Intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo especificado y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación. | .gif) | Send(IPAddress, Int32, array<Byte>[]()[], PingOptions) | Intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo con la IPAddress especificada y recibir un mensaje de respuesta de eco ICMP de ese equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación y controlar los valores de Período de vida y fragmentación para el paquete del mensaje de eco ICMP. | .gif) | Send(String, Int32, array<Byte>[]()[], PingOptions) | Intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo especificado y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación y controlar los valores de Período de vida y fragmentación para el paquete ICMP. | .gif) | SendAsync(IPAddress, Object) | Intenta enviar de forma asincrónica un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) al equipo que tiene la IPAddress especificada y recibir un mensaje de respuesta de eco ICMP correspondiente de dicho equipo. | .gif) | SendAsync(String, Object) | Intenta enviar de forma asincrónica un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) al equipo especificado y recibir un mensaje de respuesta de eco ICMP correspondiente de dicho equipo. | .gif) | SendAsync(IPAddress, Int32, Object) | Intenta enviar de forma asincrónica un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) al equipo que tiene la IPAddress especificada y recibir un mensaje de respuesta de eco ICMP correspondiente de dicho equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación. | .gif) | SendAsync(String, Int32, Object) | Intenta enviar de forma asincrónica un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) al equipo especificado y recibir un mensaje de respuesta de eco ICMP correspondiente de dicho equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación. | .gif) | SendAsync(IPAddress, Int32, array<Byte>[]()[], Object) | De forma asincrónica, intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo que tiene la IPAddress especificada, y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación. | .gif) | SendAsync(String, Int32, array<Byte>[]()[], Object) | De forma asincrónica, intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo especificado, y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación. | .gif) | SendAsync(IPAddress, Int32, array<Byte>[]()[], PingOptions, Object) | De forma asincrónica, intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo que tiene la IPAddress especificada, y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación y controlar los valores de Período de vida y fragmentación para el paquete del mensaje de eco ICMP. | .gif) | SendAsync(String, Int32, array<Byte>[]()[], PingOptions, Object) | De forma asincrónica, intenta enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) con el búfer de datos especificado al equipo especificado, y recibir el correspondiente mensaje de respuesta de eco ICMP de ese equipo. Esta sobrecarga permite especificar un valor de tiempo de espera para la operación y controlar los valores de Período de vida y fragmentación para el paquete ICMP. | .gif) | SendAsyncCancel | Cancela todas las solicitudes asincrónicas pendientes para enviar un mensaje de eco ICMP (Protocolo de mensajes de control de Internet) y recibe un mensaje de respuesta de eco ICMP correspondiente. | .gif) | ToString | Devuelve un objeto String que contiene el nombre del objeto Component, en caso de que exista. Este método no debe reemplazarse. (Se hereda de Component). | Arriba

Comentarios
Las aplicaciones utilizan la clase Ping para detectar si un equipo remoto es alcanzable. La topología de red puede determinar si Ping puede ponerse en contacto con un host remoto. La presencia y configuración de servidores proxy, equipos de traducción de direcciones de red (NAT) o firewalls pueden evitar que Ping tenga éxito. Un Ping correcto sólo indica que el host remoto se puede alcanzar en la red; no garantiza la presencia de servicios de un nivel superior (como un servidor Web) en el host remoto. Esta clase proporciona una funcionalidad similar a la herramienta de línea de comandos Ping.exe. Los métodos Send y SendAsync envían un mensaje de solicitud de eco ICPM (Protocolo de mensajes de control de Internet) a un equipo remoto y esperan un mensaje de respuesta de eco ICMP de ese equipo. Para obtener una descripción detallada de mensajes ICMP, vea RFC 792, disponible en http://www.ietf.org. Los tipos siguientes se utilizan con la clase Ping y se describen en detalle a continuación.
Nombre de tipo
|
Descripción
|
|---|
IPStatus
| Define códigos de estado que describen el resultado de un mensaje de solicitud de eco ICMP. |
PingOptions
| Permite configurar o recuperar la configuración que controla cuántas veces se puede reenviar el paquete de solicitud (Ttl) y si se puede fragmentar (DontFragment). |
PingReply
| Contiene los resultados de un mensaje de solicitud de eco ICMP. |
PingException
| Se produce si se tiene lugar un error irrecuperable. |
PingCompletedEventArgs
| Contiene los datos asociados a eventos PingCompleted que se provocan cuando finaliza o se cancela una llamada a SendAsync. |
PingCompletedEventHandler | El delegado que proporciona el método de devolución de llamada invocado cuando finaliza o se cancela una llamada a SendAsync. |
Los métodos Send y SendAsync devuelven la respuesta en un objeto PingReply. La propiedad PingReply..::.Status devuelve un valor IPStatus para indicar el resultado de la solicitud. Al enviar la solicitud, se debe especificar el equipo remoto. Se puede hacer esto proporcionando una cadena con el nombre de host, una dirección IP en formato de cadena o un objeto IPAddress. También se puede especificar alguno de los tipos siguientes de información: Datos que acompañan a la solicitud. Si se especifica buffer es posible comprobar cuánto tiempo necesita un paquete de un tamaño determinado para llegar al host remoto y volver de él, y la unidad de transmisión máxima de la ruta de acceso a la red. (Vea las sobrecargas de Send o SendAsync que toman un parámetro buffer). Si el paquete de eco ICMP se puede fragmentar durante la transmisión. (Vea la propiedad DontFragment y las sobrecargas de Send o SendAsync que toman un parámetro options). Número de veces que los nodos de enrutamiento, como enrutadores o puertas de enlace, pueden reenviar el paquete antes de que alcance el equipo de destino o sea descartado. (Vea Ttl y las sobrecargas de Send o SendAsync que toman un parámetro options). El límite de tiempo para recibir la respuesta. (Vea las sobrecargas de Send o SendAsync que toman un parámetro timeout).
La clase Ping proporciona los métodos sincrónicos y asincrónicos para enviar la solicitud. Si la aplicación debe bloquearse mientras espera una respuesta, utilice los métodos Send; estos métodos son sincrónicos. Si la aplicación no debe bloquearse, utilice los métodos SendAsync asincrónicos. Una llamada a SendAsync se ejecuta en su propio subproceso que se asigna automáticamente del grupo de subprocesos. Cuando la operación asincrónica finaliza, provoca el evento PingCompleted. Las aplicaciones utilizan un delegado de PingCompletedEventHandler para especificar el método al que se llama para eventos PingCompleted. Debe agregar un delegado de PingCompletedEventHandler al evento antes de llamar a SendAsync. El método del delegado recibe un objeto PingCompletedEventArgs que contiene un objeto PingReply que describe el resultado de la llamada a SendAsync. No puede utilizar la misma instancia de la clase Ping para generar varios mensajes de solicitud de eco ICMP simultáneos. Si se llama a Send mientras está en curso una llamada a SendAsync o si se llama varias veces a SendAsync antes de que todas las llamadas anteriores finalicen, se produce una excepción InvalidOperationException.

Ejemplos
En el siguiente ejemplo de código se muestra cómo se utiliza sincrónicamente la clase Ping.
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
// args[0] can be an IPaddress or host name.
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::Net::NetworkInformation;
using namespace System::Text;
// args[1] can be an IPaddress or host name.
int main()
{
array<String^>^args = Environment::GetCommandLineArgs();
Ping ^ pingSender = gcnew Ping;
PingOptions ^ options = gcnew PingOptions;
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options->DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
String^ data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
array<Byte>^buffer = Encoding::ASCII->GetBytes( data );
int timeout = 120;
PingReply ^ reply = pingSender->Send( args[ 1 ], timeout, buffer, options );
if ( reply->Status == IPStatus::Success )
{
Console::WriteLine( "Address: {0}", reply->Address->ToString() );
Console::WriteLine( "RoundTrip time: {0}", reply->RoundtripTime );
Console::WriteLine( "Time to live: {0}", reply->Options->Ttl );
Console::WriteLine( "Don't fragment: {0}", reply->Options->DontFragment );
Console::WriteLine( "Buffer size: {0}", reply->Buffer->Length );
}
}
En el siguiente ejemplo de código se muestra cómo se utiliza asincrónicamente la clase Ping.
using System;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Threading;
namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
public static void Main (string[] args)
{
if (args.Length == 0)
throw new ArgumentException ("Ping needs a host or IP Address.");
string who = args[0];
AutoResetEvent waiter = new AutoResetEvent (false);
Ping pingSender = new Ping ();
// When the PingCompleted event is raised,
// the PingCompletedCallback method is called.
pingSender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
// Wait 12 seconds for a reply.
int timeout = 12000;
// Set options for transmission:
// The data can go through 64 gateways or routers
// before it is destroyed, and the data packet
// cannot be fragmented.
PingOptions options = new PingOptions (64, true);
Console.WriteLine ("Time to live: {0}", options.Ttl);
Console.WriteLine ("Don't fragment: {0}", options.DontFragment);
// Send the ping asynchronously.
// Use the waiter as the user token.
// When the callback completes, it can wake up this thread.
pingSender.SendAsync(who, timeout, buffer, options, waiter);
// Prevent this example application from ending.
// A real application should do something useful
// when possible.
waiter.WaitOne ();
Console.WriteLine ("Ping example completed.");
}
private static void PingCompletedCallback (object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
Console.WriteLine ("Ping canceled.");
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
((AutoResetEvent)e.UserState).Set ();
}
// If an error occurred, display the exception to the user.
if (e.Error != null)
{
Console.WriteLine ("Ping failed:");
Console.WriteLine (e.Error.ToString ());
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
PingReply reply = e.Reply;
DisplayReply (reply);
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
public static void DisplayReply (PingReply reply)
{
if (reply == null)
return;
Console.WriteLine ("ping status: {0}", reply.Status);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}
#using <System.dll>
using namespace System;
using namespace System::Text;
using namespace System::Net;
using namespace System::Net::NetworkInformation;
using namespace System::ComponentModel;
using namespace System::Threading;
void PingCompletedCallback( Object^ sender, PingCompletedEventArgs^ e );
void DisplayReply( PingReply^ reply );
int main()
{
array<String^>^args = Environment::GetCommandLineArgs();
if ( args->Length == 1 )
throw gcnew ArgumentException( "Ping needs a host or IP Address." );
String^ who = args[ 1 ];
AutoResetEvent^ waiter = gcnew AutoResetEvent( false );
Ping ^ pingSender = gcnew Ping;
// When the PingCompleted event is raised,
// the PingCompletedCallback method is called.
pingSender->PingCompleted += gcnew PingCompletedEventHandler( PingCompletedCallback );
// Create a buffer of 32 bytes of data to be transmitted.
String^ data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
array<Byte>^buffer = Encoding::ASCII->GetBytes( data );
// Wait 12 seconds for a reply.
int timeout = 12000;
// Set options for transmission:
// The data can go through 64 gateways or routers
// before it is destroyed, and the data packet
// cannot be fragmented.
PingOptions ^ options = gcnew PingOptions( 64,true );
Console::WriteLine( "Time to live: {0}", options->Ttl );
Console::WriteLine( "Don't fragment: {0}", options->DontFragment );
// Send the ping asynchronously.
// Use the waiter as the user token.
// When the callback completes, it can wake up this thread.
pingSender->SendAsync( who, timeout, buffer, options, waiter );
// Prevent this example application from ending.
// A real application should do something useful
// when possible.
waiter->WaitOne();
Console::WriteLine( "Ping example completed." );
}
void PingCompletedCallback( Object^ /*sender*/, PingCompletedEventArgs^ e )
{
// If the operation was canceled, display a message to the user.
if ( e->Cancelled )
{
Console::WriteLine( "Ping canceled." );
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
(dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
}
// If an error occurred, display the exception to the user.
if ( e->Error != nullptr )
{
Console::WriteLine( "Ping failed:" );
Console::WriteLine( e->Error->ToString() );
// Let the main thread resume.
(dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
}
PingReply ^ reply = e->Reply;
DisplayReply( reply );
// Let the main thread resume.
(dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
}
void DisplayReply( PingReply ^ reply )
{
if ( reply == nullptr )
return;
Console::WriteLine( "ping status: {0}", reply->Status );
if ( reply->Status == IPStatus::Success )
{
Console::WriteLine( "Address: {0}", reply->Address->ToString() );
Console::WriteLine( "RoundTrip time: {0}", reply->RoundtripTime );
Console::WriteLine( "Time to live: {0}", reply->Options->Ttl );
Console::WriteLine( "Don't fragment: {0}", reply->Options->DontFragment );
Console::WriteLine( "Buffer size: {0}", reply->Buffer->Length );
}
}

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Seguridad para subprocesos
Todos los miembros static ( Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Vea también
|