65.9K
CodeProject 正在变化。 阅读更多。
Home

C# Ping 组件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.32/5 (25投票s)

2005年3月30日

2分钟阅读

viewsIcon

389525

downloadIcon

12358

一个易于使用的 C# ping 组件。

Sample Image - CSharpPing.jpg

引言

在做一个需要检查网络连接质量的项目时,我发现没有简单的方法来 ping 另一台计算机。我希望框架中(在 System.NET 命名空间中)会有一些东西可以做到这一点,因为它似乎是一个常见的需求,但我什么也没找到,所以我的搜索转向了网络。虽然我找到了一些 C# ping 示例,但它们的设计都不是很好。我想要一个 ping 实用程序,它允许我多次 ping 远程机器并以合理的方式返回 ping 统计信息(也就是说,不是我必须解析的东西),所以我决定自己制作一个。

我在网上看到的大部分 ping 代码似乎都源自 这篇 MSDN 文章,该文章由 Lance Olson 撰写,早在 .Net Beta 1 发布时就已写成(不管是否引用了他……)。我的 ping 实用程序是基于这段代码以及 这篇文章的,这篇文章由 Peter A. Bromberg 博士撰写,更新了 Olson 的代码以使其与 .NET 版本 1 兼容。使用这段代码作为起点,我试图通过创建更多类并将代码移动来使其更面向对象,这样它们就可以完成自己的工作。我认为代码现在更有意义,也更容易理解和使用。我使用 Windows 命令行 ping 命令作为我想要返回的信息的基线,所以我创建了一个 PingResponse 对象来封装所有内容并返回它,而不是 intstring。我不会详细描述代码的确切工作方式,因为它要么是不言自明的,要么只是因为你必须这样做(大多数 ICMP 类)。我包含了一个非常简单的客户端表单来展示如何异步使用 ping 实用程序,我想,您可能希望大多数时候都使用它。

使用代码

要使用此组件,只需创建一个 Ping 对象并调用 PingHostBeginPingHost 函数。

同步示例

private void Ping(string hostname)
{
    //Create ping object
    Ping netMon = new Ping();

    //Ping host (this will block until complete)
    PingResponse response = netMon.PingHost(hostname, 4);

    //Process ping response
    if (response != null)
    {
        ProcessResponse(response);
    }
}

异步示例

//Create ping object
Ping netMon = new netMon();

private void Load()
{
    //Wire events (in constructor or InitializeComponent)
    netMon.PingError += new PingErrorEventHandler(netMon_PingError);
    netMon.PingStarted += new PingStartedEventHandler(netMon_PingStarted);
    netMon.PingResponse += new PingResponseEventHandler(netMon_PingResponse);
    netMon.PingCompleted += new PingCompletedEventHandler(netMon_PingCompleted);
}

private void Ping(string hostname)
{
    //Start ping
    IAsyncResult result = netMon.BeginPingHost(
                     new AsyncCallback(EndPing), hostname, 4);
}

private void EndPing(IAsyncResult result)
{
    netMon.EndPingHost(result);
}

private void netMon_PingStarted(object sender, PingStartedEventArgs e)
{
    //Process ping started
}

private void netMon_PingResponse(object sender, PingResponseEventArgs e)
{
    //Process ping response
}

private void netMon_PingCompleted(object sender, PingCompletedEventArgs e)
{
    //Process ping completed
}

private void netMon_PingError(object sender, PingErrorEventArgs e)
{
    //Process ping error
}

已知问题 / 进一步增强

  • 第一个 ping 有时比它应该的时间长。我怀疑这是因为创建初始套接字连接花费了一些额外的时间,可以通过简单地删除第一个 ping 时间来消除。
  • 目前,您只能在触发 PingResponse 事件时取消。能够随时取消并立即处理它会很好。
  • 我真的应该为每个响应跟踪 ping 响应类型,而不是针对整组响应。我只是还没有来得及更改 PingReponse

历史

  • 版本 1.0:初始发布。
© . All rights reserved.