5,448,104 members and growing! (15,537 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » General     Intermediate

C# Ping Component

By Wesley Brown

An easy to use C# ping component.
C#, VB, Windows, .NET 1.1, .NETVisual Studio, VS.NET2003, Dev

Posted: 30 Mar 2005
Updated: 30 Mar 2005
Views: 118,586
Bookmarked: 43 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
23 votes for this Article.
Popularity: 5.08 Rating: 3.73 out of 5
3 votes, 13.0%
1
1 vote, 4.3%
2
0 votes, 0.0%
3
10 votes, 43.5%
4
9 votes, 39.1%
5

Sample Image - CSharpPing.jpg

Introduction

While working on a project that needs to check the quality of the network connection, I've found that there is no easy way to ping another computer. I expected there would be something in the framework (somewhere in the System.NET namespace) to do this as it seems like a common thing to want to do, but I could find nothing so my search turned to the web. While I was able to find some c# ping examples, none of them were very well designed. I wanted a ping utility that would let me ping a remote machine any number of times and return the ping statistics in a sensible manner (that is, not something I'd have to parse) so I decided that I'd make my own.

Most of the ping code I saw on the net seemed to be derived from this MSDN article written by Lance Olson which was written way back when for the Beta 1 release of .Net (whether it cited him or not...). I based my ping utility on this code along with this article, written by Peter A. Bromberg, PhD, which updated the Olson's code to work with .NET version 1. Using this code as a starting point I've tried to make it a little more OO by creating a couple more classes and moving the code around, so that they do their own work. I think the code makes a lot more sense now and is much easier to understand and use. I used the Windows command line ping command as a baseline for the information I wanted to return, so I created a PingResponse object that encapsulates all and gets returned instead of an int or string. I'm not going to write up a detailed description of exactly how the code works as it is either self-explanatory or simply works because that's how you have to do it (most of the ICMP class). I've included a very simple client form to show how to use the ping utility asynchronously, which I imagine, how you'd want to use it most of the time.

Using the code

To use this component simply create a Ping object and call the PingHost or BeginPingHost function.

Synchronous Example:

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);
    }
}

Asynchronous Example:

//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

}

Known Issues / Further Enhancements

  • The first ping is sometimes longer than it should be. I suspect this is because of some extra time taken to create the initial socket connection and could be eliminated by simply dropping that first ping time.
  • Currently, you can only cancel when the PingResponse event is fired. It would be nice to be able to cancel at any time and have it processed immediately.
  • I should really keep track of the ping response type per response instead of for the whole set of responses. I simply haven't got around to change the PingReponse yet.

History

  • Version 1.0: Initial release.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Wesley Brown



Occupation: Web Developer
Location: United States United States

Other popular .NET Framework articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 40 (Total in Forum: 40) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralSuggestionmemberJared Mcguire9:54 24 Apr '08  
GeneralRe: SuggestionmemberCBlackburn1:07 3 Aug '08  
GeneralAnswer: Timeoutsmemberimbored11:48 26 Mar '08  
GeneralRe: Answer: TimeoutsmemberCBlackburn1:07 3 Aug '08  
QuestionMultithread error. False success messagesmemberGokcer Gokdal10:07 26 Feb '08  
Generala lot of time...memberTal Hakemon3:43 7 Mar '07  
GeneralProblem running ur code in web applicationmemberjk8522:01 9 Jun '06  
GeneralRe: Problem running ur code in web applicationmembericebob23:50 7 Jan '07  
QuestionSocket ExceptionmemberRyan Homer6:38 11 Apr '06  
AnswerRe: Socket ExceptionmemberRyan Homer6:41 11 Apr '06  
GeneralRe: Socket ExceptionmemberWesley Brown8:00 11 Apr '06  
NewsRe: Socket ExceptionmemberRyan Homer3:58 12 Apr '06  
GeneralSynchronous timeout parameter not what it seemsmemberRoland_W3:41 6 Feb '06  
GeneralCode updatememberJohan Roos2:02 27 Jan '06  
QuestionStatistical error?memberRicardo Mendes7:19 20 Dec '05  
Generalerror?membermissjasper8:21 12 Dec '05  
GeneralSystem.Net.NetworkInformation.PingmemberKristofer Liljeblad12:28 18 Nov '05  
GeneralRe: System.Net.NetworkInformation.PingmemberDigiOz Multimedia8:38 17 Oct '07  
Generalunmanaged codememberThPloeger2:52 27 Sep '05  
GeneralWhy 60 bytes?memberEinar Kvandahl12:43 29 Jul '05  
GeneralAsync ping doesn't seem to return a PingResponsememberstevehiner13:08 1 Jul '05  
GeneralRe: Async ping doesn't seem to return a PingResponsememberWesley Brown9:17 12 Jul '05  
GeneralThanks!memberBen Buckland0:36 22 Jun '05  
GeneralResponse from nowhere...memberibleif8:26 19 Apr '05  
GeneralRe: Response from nowhere...memberTust12:09 26 Apr '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 30 Mar 2005
Editor: Sumalatha K.R.
Copyright 2005 by Wesley Brown
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project