精品收藏---C#中ping类用法的详细介绍

本文介绍了.NET Framework中的Ping类,包括其构造函数、属性、方法及事件等。提供了同步和异步发送ICMP请求的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承层次结构

命名空间: System.Net.NetworkInformation
程序集: System(在 System.dll 中)

语法


public class Ping : Component
Ping 类型公开以下成员。
名称说明
公共方法Ping初始化 Ping 类的新实例。
名称说明
受保护的属性CanRaiseEvents 获取一个指示组件是否可以引发事件的值。 (继承自 Component。)
公共属性Container 获取 IContainer,它包含Component(继承自Component。)
受保护的属性DesignMode 获取一个值,用以指示 Component 当前是否处于设计模式。(继承自Component。)
受保护的属性Events 获取附加到此 Component 的事件处理程序的列表。(继承自Component。)
公共属性Site 获取或设置 ComponentISite(继承自Component。)
名称说明
公共方法CreateObjRef 创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。(继承自MarshalByRefObject。)
公共方法Dispose() 释放由 Component 使用的所有资源。(继承自Component。)
受保护的方法Dispose(Boolean) 释放由 Ping 对象使用的非托管资源,并可根据需要释放托管资源。(重写Component.Dispose(Boolean)。)
公共方法Equals(Object) 确定指定的 Object 是否等于当前的Object(继承自Object。)
受保护的方法Finalize 在通过垃圾回收将 Component 回收之前,释放非托管资源并执行其他清理操作。(继承自Component。)
公共方法GetHashCode 用作特定类型的哈希函数。 (继承自 Object。)
公共方法GetLifetimeService 检索控制此实例的生存期策略的当前生存期服务对象。 (继承自 MarshalByRefObject。)
受保护的方法GetService 返回一个对象,该对象表示由 Component 或它的Container 提供的服务。(继承自 Component。)
公共方法GetType 获取当前实例的 Type(继承自Object。)
公共方法InitializeLifetimeService 获取控制此实例的生存期策略的生存期服务对象。 (继承自MarshalByRefObject。)
受保护的方法MemberwiseClone() 创建当前 Object 的浅表副本。(继承自Object。)
受保护的方法MemberwiseClone(Boolean) 创建当前 MarshalByRefObject 对象的浅表副本。(继承自MarshalByRefObject。)
受保护的方法OnPingCompleted引发 PingCompleted 事件。
公共方法Send(IPAddress)尝试将 Internet 控制消息协议 (ICMP) 回送消息发送到具有指定IPAddress 的计算机,并接收来自该计算机的相应 ICMP 回送答复消息。
公共方法Send(String)尝试向指定的计算机发送 Internet 控制消息协议 (ICMP) 回送消息,并从该计算机接收相应的 ICMP 回送答复消息。
公共方法Send(IPAddress, Int32)尝试将包含指定数据缓冲区的 Internet 控制消息协议 (ICMP) 回送消息发送到具有指定的IPAddress 的计算机,并接收来自该计算机的相应 ICMP 回送应答消息。使用此方法可以为操作指定一个超时值。
公共方法Send(String, Int32)尝试向指定的计算机发送 Internet 控制消息协议 (ICMP) 回送消息,并从该计算机接收相应的 ICMP 回送答复消息。使用此方法可以为操作指定一个超时值。
公共方法Send(IPAddress, Int32,Byte[])尝试将包含指定数据缓冲区的 Internet 控制消息协议 (ICMP) 回送消息发送到具有指定的IPAddress 的计算机,并接收来自该计算机的相应 ICMP 回送应答消息。此重载使您可以为操作指定一个超时值。
公共方法Send(String, Int32,Byte[])尝试用指定的数据缓冲区将 Internet 控制消息协议 (ICMP) 回显消息发送到指定计算机,然后从该计算机接收对应的 ICMP 回显回复消息。此重载使您可以为操作指定一个超时值。
公共方法Send(IPAddress, Int32,Byte[], PingOptions)尝试将包含指定数据缓冲区的 Internet 控制消息协议 (ICMP) 回送消息发送到具有指定IPAddress 的计算机,并接收来自该计算机的相应 ICMP 回送答复消息。此重载允许您指定操作的超时值,并控制 ICMP 回显消息数据包的碎片和生存时间值。
公共方法Send(String, Int32,Byte[], PingOptions)尝试用指定的数据缓冲区将 Internet 控制消息协议 (ICMP) 回显消息发送到指定计算机,然后从该计算机接收对应的 ICMP 回显回复消息。此重载允许您指定操作的超时值,并控制 ICMP 数据包的碎片和生存时间值。
公共方法SendAsync(IPAddress, Object)尝试以异步方式向指定 IPAddress 的计算机发送 Internet 控制消息协议 (ICMP) 回送消息,并从该计算机接收相应的 ICMP 回送答复消息。
公共方法SendAsync(String, Object)尝试以异步方式向指定的计算机发送 Internet 控制消息协议 (ICMP) 回送消息,并从该计算机接收相应的 ICMP 回送答复消息。
公共方法SendAsync(IPAddress, Int32, Object)尝试以异步方式向指定 IPAddress 的计算机发送 Internet 控制消息协议 (ICMP) 回送消息,并从该计算机接收相应的 ICMP 回送答复消息。此重载使您可以为操作指定一个超时值。
公共方法SendAsync(String, Int32, Object)尝试以异步方式向指定的计算机发送 Internet 控制消息协议 (ICMP) 回送消息,并从该计算机接收相应的 ICMP 回送答复消息。此重载使您可以为操作指定一个超时值。
公共方法SendAsync(IPAddress, Int32,Byte[], Object)尝试用指定的数据缓冲区以异步方式将 Internet 控制消息协议 (ICMP) 回显消息发送到具有指定的IPAddress 的计算机,并从该计算机接收对应的 ICMP 回显回复消息。此重载使您可以为操作指定一个超时值。
公共方法SendAsync(String, Int32,Byte[], Object)尝试用指定的数据缓冲区以异步方式将 Internet 控制消息协议 (ICMP) 回显消息发送到指定计算机,并从该计算机接收对应的 ICMP 回显回复消息。此重载使您可以为操作指定一个超时值。
公共方法SendAsync(IPAddress, Int32,Byte[], PingOptions, Object)尝试用指定的数据缓冲区以异步方式将 Internet 控制消息协议 (ICMP) 回显消息发送到具有指定的IPAddress 的计算机,并从该计算机接收对应的 ICMP 回显回复消息。此重载允许您指定操作的超时值,并控制 ICMP 回显消息数据包的碎片和生存时间值。
公共方法SendAsync(String, Int32,Byte[], PingOptions, Object)尝试用指定的数据缓冲区以异步方式将 Internet 控制消息协议 (ICMP) 回显消息发送到指定计算机,并从该计算机接收对应的 ICMP 回显回复消息。此重载允许您指定操作的超时值,并控制 ICMP 数据包的碎片和生存时间值。
公共方法SendAsyncCancel取消所有挂起的发送 Internet 控制消息协议 (ICMP) 回送消息并接收相应 ICMP 回送答复消息的异步请求。
公共方法ToString 返回包含 Component 的名称的String(如果有)。不应重写此方法。(继承自 Component。)
名称说明
公共事件Disposed 当通过调用 Dispose 方法释放组件时发生。(继承自Component。)
公共事件PingCompleted当发送 Internet 控制消息协议 (ICMP) 回送消息并接收相应 ICMP 回送答复消息的异步操作完成或被取消时发生。

应用程序使用 Ping 类检测是否可访问远程计算机。

网络拓扑可确定 Ping 是否可成功联系远程主机。如果存在或配置了代理服务器、网络地址转换 (NAT) 设备或防火墙,可能会妨碍Ping 成功。Ping 成功只是表示可以通过网络访问远程主机;但并不保证远程主机上存在更高级别的服务(例如 Web 服务器)。

此类提供的功能类似于 Ping.exe 命令行工具。 SendSendAsync 方法将 Internet 控制消息协议 (ICMP) 回送请求消息发送到远程计算机并等待来自该计算机的 ICMP 回送答复消息。有关 ICMP 消息的详细说明,请参见 RFC 792,这可以在http://www.ietf.org 上找到。

以下类型与 Ping 类一起使用,详见下文。

类型名称

说明

IPStatus

定义描述 ICMP 回送请求消息结果的状态代码。

PingOptions

允许配置或检索控制请求数据包可以转发的次数 (Ttl) 和数据包是否可以分段 (DontFragment) 的设置。

PingReply

包含 ICMP 回送请求的结果。

PingException

发生不可恢复的错误时引发。

PingCompletedEventArgs

包含与 PingCompleted 事件关联的数据,这些事件在SendAsync 调用完成或被取消时引发。

PingCompletedEventHandler

提供在 SendAsync 调用完成或被取消时调用的回调方法的委托。

SendSendAsync 方法在PingReply 对象中返回答复。PingReply.Status 属性返回IPStatus 值以指示请求结果。

发送请求时,必须指定远程计算机。 为此可以提供主机名字符串、字符串格式的 IP 地址或 IPAddress 对象。

还可以指定以下任何类型的信息:

  • 与请求一起发送的数据。 指定 buffer 可了解特定大小的数据包传送到或来自远程主机所需的时间量,以及网络路径的最大传输单位。(请参见带buffer 参数的SendSendAsync 重载。)

  • ICMP 回送数据包在传输时是否可以分段。 (请参见 DontFragment 属性和带options 参数的SendSendAsync 重载。)

  • 路由节点(如路由器或网关)在数据包到达目标计算机或被丢弃之前可以转发数据包的次数。(请参见Ttl 和带options 参数的SendSendAsync 重载。)

  • 必须收到答复的时间限制。 (请参见带 timeout 参数的 SendSendAsync 重载。)

Ping 类提供了发送请求的同步方法和异步方法。如果应用程序应在等待答复时阻止,请使用Send 方法;这些方法是同步的。如果应用程序不应阻止,请使用异步SendAsync 方法。SendAsync 调用在它自己的、从线程池自动分配的线程中执行。当异步操作完成时,它会引发 PingCompleted 事件。应用程序使用PingCompletedEventHandler 委托指定为PingCompleted 事件调用的方法。在调用 SendAsync 之前,必须为该事件添加PingCompletedEventHandler 委托。该委托的方法收到一个 PingCompletedEventArgs 对象,该对象包含一个描述SendAsync 调用结果的PingReply 对象。

不能使用 Ping 类的同一实例生成多个同时 ICMP 回送请求。SendAsync 调用正在进行时调用Send 或者在所有以前的调用完成前多次调用SendAsync 将导致InvalidOperationException

示例

下面的代码示例演示如何同步使用 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);
            }
        }
    }
}


下面的代码示例演示如何异步使用 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);
            }
        }
    }
}


.NET Framework
受以下版本支持:4、3.5、3.0、2.0
.NET Framework Client Profile
受以下版本支持:4、3.5 SP1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值