Ping class usage in C #

Source: Internet
Author: User
Tags echo message

Inheritance hierarchy

--------------------------------------------------------------------------------

System. Object
System. externalbyrefobject
System. ComponentModel. Component
System. Net. NetworkInformation. Ping


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

Syntax


--------------------------------------------------------------------------------

Public class Ping: Component
The following members are public for the Ping type.
Constructor

--------------------------------------------------------------------------------

Description
Ping the new instance that initializes the Ping class.

Attribute

--------------------------------------------------------------------------------

Description
CanRaiseEvents gets a value indicating whether a component can trigger an event. (Inherited from Component .)
The Container obtains the IContainer, which contains the Component. (Inherited from Component .)
DesignMode gets a value to indicate whether the Component is in the design mode. (Inherited from Component .)
Events gets the list of Event Handlers appended to this Component. (Inherited from Component .)
Site to obtain or set the ISite of Component. (Inherited from Component .)

Method

--------------------------------------------------------------------------------

Description
CreateObjRef creates an object that contains all the information required to generate a proxy for communication with a remote object. (Inherited from MarshalByRefObject .)
Dispose () releases all resources used by Component. (Inherited from Component .)
Dispose (Boolean) releases the unmanaged resources used by the Ping object and releases the managed resources as needed. (Override Component. Dispose (Boolean ).)
Equals (Object) determines whether the specified Object is equal to the current Object. (Inherited from Object .)
Finalize releases unmanaged resources and performs other cleanup operations before it recycles Component. (Inherited from Component .)
GetHashCode is used as a hash function of a specific type. (Inherited from Object .)
GetLifetimeService searches the service objects that control the current lifetime of the Instance's lifetime policy. (Inherited from MarshalByRefObject .)
GetService returns an object that represents the service provided by Component or its Container. (Inherited from Component .)
GetType: Get the Type of the current instance. (Inherited from Object .)
InitializeLifetimeService gets the lifetime service object that controls the lifetime policy of this instance. (Inherited from MarshalByRefObject .)
MemberwiseClone () creates a superficial copy of the current Object. (Inherited from Object .)
MemberwiseClone (Boolean) creates a superficial copy of the currently stored albyrefobject object. (Inherited from MarshalByRefObject .)
OnPingCompleted triggers the PingCompleted event.
Send (IPAddress) attempts to Send Internet Control Message Protocol (ICMP) to a computer with the specified IPAddress, and receives the corresponding ICMP return reply message from the computer.
Send (String) attempts to Send an Internet Control Message Protocol (ICMP) Send message to the specified computer, and receives the corresponding ICMP return reply message from the computer.
Send (IPAddress, Int32) attempts to Send an Internet Control Message Protocol (ICMP) that contains the specified data buffer to a computer with the specified IPAddress, and receive the corresponding ICMP reply message from the computer. You can use this method to specify a timeout value for the operation.
Send (String, Int32) attempts to Send an Internet Control Message Protocol (ICMP) Send message to the specified computer, and receives the corresponding ICMP return reply message from the computer. You can use this method to specify a timeout value for the operation.
Send (IPAddress, Int32, Byte []) attempts to Send an Internet Control Message Protocol (ICMP) that contains the specified data buffer to a computer with the specified IPAddress, and receive the corresponding ICMP reply message from the computer. This overload allows you to specify a timeout value for the operation.
Send (String, Int32, Byte []) tries to Send the Internet Control Message Protocol (ICMP) echo message to the specified computer with the specified data buffer, then, the computer receives the corresponding ICMP echo reply message. This overload allows you to specify a timeout value for the operation.
Send (IPAddress, Int32, Byte [], PingOptions) tries to Send the Internet Control Message Protocol (ICMP) that contains the specified data buffer to a computer with the specified IPAddress, and receive the corresponding ICMP reply message from the computer. This overload allows you to specify the operation timeout value and control the fragmentation and survival time of the ICMP echo message packet.
Send (String, Int32, Byte [], PingOptions) tries to Send the Internet Control Message Protocol (ICMP) echo message to the specified computer with the specified data buffer, then, the computer receives the corresponding ICMP echo reply message. This overload allows you to specify the operation timeout value and control the fragmentation and survival time value of ICMP packets.
SendAsync (IPAddress, Object) tries to asynchronously send an Internet Control Message Protocol (ICMP) send message to the computer with the specified IPAddress, and receives the corresponding ICMP reply message from the computer.
SendAsync (String, Object) tries to asynchronously send an Internet Control Message Protocol (ICMP) send message to the specified computer, and receives the corresponding ICMP return reply message from the computer.
SendAsync (IPAddress, Int32, Object) tries to asynchronously send an Internet Control Message Protocol (ICMP) send message to the computer with the specified IPAddress, and receives the corresponding ICMP reply message from the computer. This overload allows you to specify a timeout value for the operation.
SendAsync (String, Int32, Object) tries to send an Internet Control Message Protocol (ICMP) send message to the specified computer asynchronously, and receives the corresponding ICMP return reply message from the computer. This overload allows you to specify a timeout value for the operation.
SendAsync (IPAddress, Int32, Byte [], Object) tries to use the specified data buffer to asynchronously send an Internet Control Message Protocol (ICMP) echo message to a computer with the specified IPAddress, and receive the corresponding ICMP echo reply message from the computer. This overload allows you to specify a timeout value for the operation.
SendAsync (String, Int32, Byte [], Object) tries to use the specified data buffer to asynchronously send the Internet Control Message Protocol (ICMP) echo message to the specified computer, and receive the corresponding ICMP echo reply message from the computer. This overload allows you to specify a timeout value for the operation.
SendAsync (IPAddress, Int32, Byte [], PingOptions, Object) tries to use the specified data buffer to asynchronously control the Internet Message Protocol (ICMP) the echo message is sent to a computer with the specified IPAddress, and the computer receives the corresponding ICMP echo response message. This overload allows you to specify the operation timeout value and control the fragmentation and survival time of the ICMP echo message packet.
SendAsync (String, Int32, Byte [], PingOptions, Object) tries to asynchronously send an Internet Control Message Protocol (ICMP) echo message to the specified computer using the specified data buffer, and receive the corresponding ICMP echo reply message from the computer. This overload allows you to specify the operation timeout value and control the fragmentation and survival time value of ICMP packets.
SendAsyncCancel cancels all pending asynchronous requests for sending Internet Control Message Protocol (ICMP) replies and receiving corresponding ICMP replies.
ToString returns the String containing the Component name (if any ). This method should not be rewritten. (Inherited from Component .)

Event

--------------------------------------------------------------------------------

Description
Disposed occurs when a component is released by calling the Dispose method. (Inherited from Component .)
PingCompleted occurs when an asynchronous operation is completed or canceled to send an Internet Control Message Protocol (ICMP) return message and receive the corresponding ICMP return reply message.

Remarks

--------------------------------------------------------------------------------

Applications use the Ping class to check whether remote computers are accessible.

The network topology determines whether the Ping operation can successfully contact the remote host. If a proxy server, network address translation (NAT) device, or firewall is configured, the Ping may fail. A successful Ping only indicates that the remote host can be accessed through the network, but it does not guarantee that there are more advanced services (such as Web servers) on the remote host ).

This class provides functions similar to the Ping.exe command line tool. The Send and SendAsync Methods Send Internet Control Message Protocol (ICMP) Send request messages to a remote computer and wait for ICMP reply messages from the computer. For a detailed description of ICMP messages, see RFC 792, which can be found on the http://www.ietf.org.

The following types are used with the Ping class. For more information, see the following section.

Type name
Description
 
IPStatus
Defines the status code that describes the message result of an ICMP return request.
 
PingOptions
Allows you to configure or retrieve settings that control the number of times (Ttl) that request data packets can be forwarded and whether data packets can be segmented (DontFragment.
 
PingReply
Contains the results of the ICMP return request.
 
PingException
It is triggered when an unrecoverable error occurs.
 
PingCompletedEventArgs
Contains the data associated with the PingCompleted event, which is triggered when the SendAsync call is completed or canceled.
 
PingCompletedEventHandler
Provides the delegate of the callback method called when the SendAsync call is completed or canceled.
 

The Send and SendAsync Methods return responses in the PingReply object. The PingReply. Status attribute returns the IPStatus value to indicate the request result.

When sending a request, you must specify a remote computer. Therefore, you can provide 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 sent together with the request. Specify the buffer to know the time required for transmitting data packets of a specific size to or from a remote host, and the maximum transmission unit of the network path. (See the Send or SendAsync overload with buffer parameters .)

Whether ICMP return data packets can be segmented during transmission. (See the DontFragment attribute and the Send or SendAsync overload with the options parameter .)

The number of times a route node (such as a router or gateway) forwards data packets before they reach the target computer or are discarded. (See Ttl and the Send or SendAsync overload with options parameters .)

The time limit for receiving replies. (See the Send or SendAsync overload with the timeout parameter .)

Ping provides synchronous and asynchronous methods for sending requests. If the application should be blocked while waiting for a response, use the Send method, which is synchronous. If the application should not be blocked, use the asynchronous SendAsync method. SendAsync is called in its own thread that is automatically allocated from the thread pool. When the asynchronous operation is complete, it will trigger the PingCompleted event. The application uses the PingCompletedEventHandler delegate to specify the method called for the PingCompleted event. Before calling SendAsync, you must add the PingCompletedEventHandler delegate for the event. The delegate method receives a PingCompletedEventArgs object, which contains a PingReply object that describes the SendAsync call result.

You cannot use the same instance of the Ping class to generate multiple simultaneous ICMP return requests. When SendAsync calls SendAsync while sending or multiple calls to SendAsync before all previous calls are completed, InvalidOperationException occurs.

Example

--------------------------------------------------------------------------------

The following code example demonstrates how to synchronize the Ping class.

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 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ";
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 );
}
}
}
}


The following code example demonstrates how to use 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 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ";
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 route ways 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 shoshould 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.
(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 );
}
}
}
}

Author: a125138

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.