Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Asynchronous Ping using C#

In this C# tutorial we're going to learn how to ping a host over a network or the Internet using C#. Furthermore the ping is going to be executed asynchronously so that our application doesn't have to wait for the ping.

On Monday, October 8th 2007 at 10:43 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.5 with 23 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

Pinging

A good analogy for would be sending a package with a timer in it to a destination and then back to you. When you get the package back you look at the timer to see how long it took for it to make the trip. If you don't get it back in a decent amount of time, you mark it as lost, and take it with the courier.
We're all used to the ping command in the MS-DOS command prompt, and what we're going to build today it's going to look much like it:

Ping Command Prompt


Designing the application

Start Visual Studio 2005 or whatever you prefer to use, and put up a form similar to the one below. The important controls are the TextBoxes txtIP, txtResponse (multiline) and a Button btnPing.

Ping Form


Preparing the class

Before I go any further with showing off the SendPing() method and the related events, we need to add the two using statements, since we'll be using an async call, we need System.Threading, and since we'll need access to several networking objects, we need System.Net.NetworkInformation:


using System.Threading;

using System.Net.NetworkInformation;



Inside the class declare these two objects that we'll want accessible later from inside the methods:


// Counts the pings

private int pingsSent;

// Can be used to notify when the operation completes

AutoResetEvent resetEvent = new AutoResetEvent(false);



Now we can move onto coding.


Writing the code

We'll start with the Click event of btnPing where everything starts:


private void btnPing_Click(object sender, EventArgs e)

{

    // Reset the number of pings

    pingsSent = 0;

    // Clear the textbox of any previous content

    txtResponse.Clear();

    txtResponse.Text += "Pinging " + txtIP.Text + " with 32 bytes of data:\r\n\r\n";

    // Send the ping

    SendPing();

}



There we prepare things up, and call the SendPing() method:


private void SendPing()

{

    System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();

 

    // Create an event handler for ping complete

    pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete);

 

    // Create a buffer of 32 bytes of data to be transmitted.

    byte[] packetData = Encoding.ASCII.GetBytes("................................");

 

    // Jump though 50 routing nodes tops, and don't fragment the packet

    PingOptions packetOptions = new PingOptions(50, true);

 

    // Send the ping asynchronously

    pingSender.SendAsync(txtIP.Text, 5000, packetData, packetOptions, resetEvent);

}


First of all you probably noticed that we still declare the Ping object using its full namespace. That's because otherwise the compiler will confuse it with the Ping namespace. On the line following that, we set an event handler for PingCompleted to pingSender_Complete, and that's where our next chunk of code will be located. The event will fire, as you might've guessed, when the packet comes back, or when it doesn't and the request has timed out. packetData is the content of the package. We made it 32 bytes in size by having 32 characters in it. It doesn't matter what the characters are, so you can put it your little easter egg in there if you wish to. We don't want the packet to be defragmented, since the returned result would not be a true number of milliseconds that the packet took to go to the destination and back. Finally the last method sends the ping to the desired host (IP address or host name), with a timeout of 5000 milliseconds and the options specified earlier (should not exceed 50 routing nodes, and should not be fragmented.)

This moves us to our next piece of code, which is the pingSender_Complete event:


private void pingSender_Complete(object sender, PingCompletedEventArgs e)

{

    // If the operation was canceled, display a message to the user.

    if (e.Cancelled)

    {

        txtResponse.Text += "Ping was canceled...\r\n";

 

        // The main thread can resume

        ((AutoResetEvent)e.UserState).Set();

    }

    else if (e.Error != null)

    {

        txtResponse.Text += "An error occured: " + e.Error + "\r\n";

 

        // The main thread can resume

        ((AutoResetEvent)e.UserState).Set();

    }

    else

    {

        PingReply pingResponse = e.Reply;

        // Call the method that displays the ping results, and pass the information with it

        ShowPingResults(pingResponse);

    }

}



This piece of code fires when the package got back or when the timeout arrived. Depending on the response, we either show the negative result and tell the main thread it can resume, or call the method that displays the results, which is ShowPingResults():


public void ShowPingResults(PingReply pingResponse)

{

    if (pingResponse == null)

    {

        // We got no response

        txtResponse.Text += "There was no response.\r\n\r\n";

        return;

    }

    else if (pingResponse.Status == IPStatus.Success)

    {

        // We got a response, let's see the statistics

        txtResponse.Text += "Reply from " + pingResponse.Address.ToString() + ": bytes=" + pingResponse.Buffer.Length + " time=" + pingResponse.RoundtripTime + " TTL=" + pingResponse.Options.Ttl + "\r\n";

    }

    else

    {

        // The packet didn't get back as expected, explain why

        txtResponse.Text += "Ping was unsuccessful: " + pingResponse.Status + "\r\n\r\n";

    }

    // Increase the counter so that we can keep track of the pings sent

    pingsSent++;

    // Send 4 pings

    if (pingsSent < 4)

    {

        SendPing();

    }

}



Here we do some additional checking. First we make sure that we got the parameter passed in correctly - pingResponse of type PingReply - since it holds all the information about how the package got back. We display that information much like MS-DOS displays it when using the ping command but without the final statistics. However, just like the MS-DOS ping command works by default, we do run 4 pings per each request, so at the end of ShowPingResults() we call the SendPing() method all over again, unless we already did that 4 times.

You're now ready to compile, run and do some pinging! The example below pinged the yahoo.com server IP. Just don't do it too much or you might take the Yahoo server down. Yeah, right ;-).

Application Ping
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by sandip jadhav on Friday, October 19th 2007 at 02:42 PM

Nice program helped us in implementing Firewall in C#

by Veres Zoltan on Tuesday, February 26th 2008 at 02:52 PM

Exceptional piece of article,exactly this code what i need for my licence work.
Thank you and publish meny article az possible :D

by Mehmet ali on Sunday, May 11th 2008 at 07:54 AM

çok teşekkür ederim tank you
I love geekpedia

by Rosen Rusev on Sunday, August 10th 2008 at 05:16 AM

It's really fast pinger.
It makes all four pings at once.

by Michał on Wednesday, February 11th 2009 at 03:40 AM

dude, your ping is not async at all. AutoResetEvent is not needed here. Plus "Ping" class implements IDisposable and you don't invoke Dispose method anywhere

by mnn on Wednesday, May 13th 2009 at 03:15 PM

Agreed with MichaÅ. You don't even use resetEvent.WaitOne, which defeats purpose of AutoResetEvent

by noone on Saturday, June 20th 2009 at 07:21 AM

this has been copied from MSDN :x

by suchint on Monday, September 14th 2009 at 02:45 PM

gr8 man!!! wether it is copied from somewhere ,doesnt matter ,but important is way which u elborate!!!!

by Nisar on Thursday, October 1st 2009 at 06:21 AM

Great, i am using this code now to solve my problems........ thnx

by Nisar on Thursday, October 1st 2009 at 06:21 AM

Great, i am using this code now to solve my problems........ thnx

by anon on Monday, November 2nd 2009 at 12:29 PM

Does not work.
Took 2-3 minutes solid to compile.
Only shows the first line "...32 bytes of data..." then just sits there.
Pinged various internal LAN IPs and local IP.
Going elsewhere for async tutorial.
Thanks for trying.

by Mauhen on Wednesday, December 23rd 2009 at 09:18 AM

Great piece of code, worked first time, no bugs, thank you very much.

by scott on Thursday, February 11th 2010 at 08:06 PM

Worked first time I compiled it on Visual C# 2008 Express Edition. Made some changes to mine to maintain a history ....

by Jim on Friday, March 26th 2010 at 01:42 PM

Thanks! Good bacic code. Just what I needed!

by KangWooSauk on Wednesday, May 19th 2010 at 03:20 AM

It's good source code!
Thanks!!

by sithick on Thursday, May 27th 2010 at 02:30 AM

It's a best source code!!!!!

Thanks a lot....

by Atique on Wednesday, March 2nd 2011 at 02:53 AM

A much simpler and nice piece of code. The better thing is that is really understandable.

Thanx

by Asniza on Wednesday, July 13th 2011 at 11:04 PM

yeah excellent ,,,

thanks for sharing,,

by ugg boots on Monday, August 1st 2011 at 02:32 AM


[url=http://www.uggnetstore.com ]Australia Sheepskin Ugg Boots on sale,you can buy cheap ugg boots,ugg boots 5815,discount ugg boots 5825,ugg boots 5823,ugg boots for womens,Australia Sheepskin Ugg Boots,ugg winter boots,UGG Bailey Button,UGG Classic Short,UGG Classic Tall,Ugg Classic Cardy.[/url]
[url=http://www.uggnetstore.com/ ]ugg boots[/url]
[url=http://www.uggnetstore.com/ ]cheap uggs[/url]
[url=http://www.uggnetstore.com/ ]UGG Bailey Button[/url]
[url=http://www.uggnetstore.com/ ]UGG Classic Short[/url]
[url=http://www.uggnetstore.com/ ]UGG Classic Short[/url]
[url=http://www.uggnetstore.com/ ]Ugg Classic Cardy[/url]
[url=http://www.uggnetstore.com/ ]ugg winter boots[/url]
[url=http://www.uggnetstore.com/ ]Australia Sheepskin Ugg Boots on sale[/url]
[url=http://www.uggentityshop.com ]Australia Sheepskin Ugg Boots on sale,you can buy cheap ugg boots,ugg boots 5815,discount ugg boots 5825,ugg boots 5823,ugg boots for womens,Australia Sheepskin Ugg Boots,ugg winter boots,UGG Bailey Button,UGG Classic Short,UGG Classic Tall,Ugg Classic Cardy.[/url]
[url=http://www.uggentityshop.com/ ]UGG Bailey Button[/url]
[url=http://www.uggentityshop.com/ ]UGG Classic Short[/url]
[url=http://www.uggentityshop.com/ ]ugg boots[/url]
[url=http://www.uggentityshop.com/ ]cheap uggs[/url]
[url=http://www.uggentityshop.com/ ]Ugg Classic Cardy[/url]
[url=http://www.uggentityshop.com/ ]ugg winter boots[/url]
[url=http://www.uggentityshop.com/ ]Australia Sheepskin Ugg Boots on sale[/url]
[url=http://www.netbuyugg.com ]Australia Sheepskin Ugg Boots on sale,you can buy cheap ugg boots,ugg boots 5815,discount ugg boots 5825,ugg boots 5823,ugg boots for womens,Australia Sheepskin Ugg Boots,ugg winter boots,UGG Bailey Button,UGG Classic Short,UGG Classic Tall,Ugg Classic Cardy.[/url]
[url=http://www.netbuyugg.com/ ]ugg winter boots[/url]
[url=http://www.netbuyugg.com/ ]Australia Sheepskin Ugg Boots on sale[/url]
[url=http://www.netbuyugg.com/ ]ugg boots[/url]
[url=http://www.netbuyugg.com/ ]cheap uggs[/url]
[url=http://www.netbuyugg.com/ ]UGG Bailey Button[/url]
[url=http://www.netbuyugg.com/ ]UGG Classic Short[/url]
[url=http://www.netbuyugg.com/ ]UGG Classic Short[/url]
[url=http://www.netbuyugg.com/ ]Ugg Classic Cardy[/url]
[url=http://www.ibuyugg.com ]Welcome to the cheap uggs|a nature shop website offering a comprehensive range of sheepskin cheap uggs and ugg boots. Aside from our highly competitive pricing,we offer free fast shipping world wide included in all of our prices and a 100% products original package of ugg boots.[/url]
[url=http://www.ibuyugg.com/ugg-classic-short-boots.html ]ugg classic short[/url]
[url=http://www.ibuyugg.com/ ]wholesale ugg boots[/url]
[url=http://www.ibuyugg.com/ ]ugg boots[/url]
[url=http://www.ibuyugg.com/ ]cheap uggs[/url]
[url=http://www.ibuyugg.com/ ]ugg boots sale[/url]
[url=http://www.uggbootsgood.com ]Authentic cheap UGGs store,buy latest styles and cheap UGG Boots.welcome to our professional UGGs for cheap store|offering UGG Boots sale and UGGs outlet on all styles|save up to 70%|free shipping and fast delivery.[/url]
[url=http://www.uggbootsgood.com/ ]ugg boots online[/url]
[url=http://www.uggbootsgood.com/ ]ugg boots sale[/url]
[url=http://www.uggbootsgood.com/ ]ugg boots outlet[/url]
[url=http://www.uggbootsgood.com/ ]uggs for cheap[/url]
[url=http://www.uggbootsgood.com/ ]uggs on sale[/url]
[url=http://www.uggbootsgood.com/ ]ugg australia[/url]
[url=http://www.uggbootsgood.com/ ]ugg boots[/url]
[url=http://www.esaleugg.com ]Welcome to the cheap uggs,a nature shop website offering a comprehensive range of sheepskin cheap uggs and ugg boots. Aside from our highly competitive pricing|we offer free fast shipping world wide included in all of our prices and a 100% products original package of ugg boots.[/url]
[url=http://www.esaleugg.com/ ]uggs outlet[/url]
[url=http://www.esaleugg.com/ ]wholesale ugg boots[/url]
[url=http://www.esaleugg.com/ ]ugg boots[/url]
[url=http://www.esaleugg.com/ ]cheap uggs[/url]
[url=http://www.esaleugg.com/ ]uggs for cheap[/url]
[url=http://www.esaleugg.com/ ]ugg boots sale[/url]
[url=http://www.prettyuggboots.com ]prettyuggboots.com ugg boots website sales AAA replica ugg boots ,50%-70% Off Freeshipping cheap ugg boot,fake ugg boots ,UGG sheepskin shoes,UGG celtic sheepskin,Best after-sale service and fast delivery![/url]
[url=http://www.prettyuggboots.com/ ]ugg boots website[/url]
[url=http://www.prettyuggboots.com/ ]replica ugg boots[/url]
[url=http://www.prettyuggboots.com/ ]ugg boots[/url]
[url=http://www.prettyuggboots.com/ ]cheap uggs[/url]
[url=http://www.prettyuggboots.com/ ]cheap ugg boot[/url]
[url=http://www.prettyuggboots.com/ ]fake ugg boots[/url]
[url=http://www.prettyuggboots.com/ ]wholesale ugg boots[/url]

by Protips on Saturday, August 6th 2011 at 11:55 AM

This is great. Simple and what i need. thanks.
http://www.protips.info

by king on Friday, September 23rd 2011 at 04:12 AM

You can download video tutorial for PING,IPsniffer,Network Status
from
http://sharecash.org/download.php?file=2306270

by Local Search Rankings on Monday, December 12th 2011 at 06:22 AM

Diplomatical I definitely liked denotive it. This communicating provided by you is rale micturate for prudish cerebration. and I dont believe omens its just the narrow thinking.It is a scientific eare each and every thing has a soild reason cfor its existance.

by Used Pallet Racking on Saturday, December 17th 2011 at 05:14 PM

Diplomatical I definitely liked denotive it. This communicating provided by you is rale micturate for prudish cerebration. and I dont believe omens its just the narrow thinking.It is a scientific eare each and every thing has a soild reason cfor its existance.

by GenF20 Plus on Monday, December 19th 2011 at 04:46 PM

This communicating provided by you is rale micturate for prudish cerebration. and I dont believe omens its just the narrow thinking.

by Dental White on Monday, December 19th 2011 at 05:02 PM

This communicating provided by you is rale micturate for prudish cerebration. and I dont believe omens its just the narrow thinking.

by Teeth Whitening Reviews on Monday, December 19th 2011 at 05:04 PM

This is cool. I just wanted to let you know how much I enjoy reading the blog, and hope you keep posting such great material.

by Best Diet Pills on Monday, December 19th 2011 at 05:05 PM

This is cool. I just wanted to let you know how much I enjoy reading the blog, and hope you keep posting such great material.

by HGH Advanced on Monday, December 19th 2011 at 05:10 PM

The information and the detail were just perfect.

by Proactol Plus on Monday, December 19th 2011 at 05:11 PM

The information and the detail were just perfect.

by Botanical White on Monday, December 19th 2011 at 05:11 PM

The information and the detail were just perfect.

by Pure Acai Berry Max on Monday, December 19th 2011 at 05:13 PM

Do you know how the random.next selects the random number? Meaning Does every possibility(number) have an equal chance/probability of occurring? I am trying to have something specific done 65% of the time it is prompted

by Ultimate Maqui Berry on Monday, December 19th 2011 at 05:14 PM

Do you know how the random.next selects the random number? Meaning Does every possibility(number) have an equal chance/probability of occurring? I am trying to have something specific done 65% of the time it is prompted

by Meratol on Monday, December 19th 2011 at 05:16 PM

My solutution is for those cases you need a good "start" seed for a long series of random numbers, because the numbers in the random class is random itself. The most important thing is NOT to shuffle in the random number array BUT to get different startpoints in the random array.

by funeral flower arrangements on Saturday, January 21st 2012 at 05:23 PM

Interesting topic what you have shared with us. Your writing skill is really very appreciative. I love when you share your views through the best articles.Keep sharing and posting articles like these.This article has helped me a lot.Keep posting this stuff.

by GD Poker on Sunday, January 22nd 2012 at 07:20 PM

Helpful info. Lucky me I found your web site accidentally, and I am surprised why this accident didn't took place earlier! I bookmarked it.

by Rice Crispy Treats on Sunday, January 29th 2012 at 03:57 PM

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.

by Free RingtonesFor Virgin Mobile on Tuesday, January 31st 2012 at 07:23 PM

Great post full of useful tips! My site is fairly new and I am also having a hard time getting my readers to leave comments. Analytics shows they are coming to the site but I have a feeling “nobody wants to be first”.

by on Thursday, February 2nd 2012 at 06:53 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by gel memory foam on Sunday, February 19th 2012 at 03:09 PM

You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand.

by where to surplus ink cartridge best buy on Wednesday, February 22nd 2012 at 09:49 PM

Truly impressive and nice information,it is always good material to learn this post increases my knowledge.

Appreciate it...

by the best places to s on Sunday, February 26th 2012 at 09:39 PM

I simply cant stop here. Its so cool, so filled with information i just didnt know. Im glad to determine that folks have been covering this challenge ordinary smart way, showing most of us different sides to barefoot jogging. Youre an incredible blogger. Please thanks. I cant wait to see whats next.

by the best p on Sunday, February 26th 2012 at 09:46 PM

This can be this type of great resource that you'll be supplying and you simply provide away absolutely free. I adore seeing websites that be aware of the dependence on supplying an outstanding resource no cost. Appreciation for this glorious resource!


by Granny Pussy on Monday, May 21st 2012 at 04:23 PM

I could also gain several of my ranches for marketing substance for you all budy who come up here. i think so it is very useful and knowledgeable. I would like to thank you for the efforts.

by Pussy Tube on Tuesday, May 29th 2012 at 07:09 PM

nice one i like it very much please keep posting thank you .

by pornhub on Friday, June 1st 2012 at 04:25 AM

cool post its very informative post i like it so much :)).

by on Monday, June 11th 2012 at 06:26 PM

asdads

by Ryan Wuerch on Sunday, June 24th 2012 at 06:52 AM

When you get the package back you look at the timer to see how long it took for it to make the trip. If you don't get it back in a decent amount of time, you mark it as lost, and take it with the courier.

by Amin on Monday, March 4th 2013 at 12:27 PM

I'm from Iran, very thank for your perfect site.

by Amin on Monday, March 4th 2013 at 12:27 PM

I'm from Iran, very thank for your perfect site.

by Amin on Monday, March 4th 2013 at 12:27 PM

I'm from Iran, very thank for your perfect site.

by Margahayuland on Sunday, June 9th 2013 at 07:27 AM

back you look at the timer to see how long it took for it to make the trip
http://sooboos.com/margahayuland/margahayuland-42-tahun-membangun-ruang-hidup.php
http://sooboos.com/situs-berita/penting-panas-perlu-dan-seruu.php
http://sooboos.com
http://wadahpromoindonesia.blogspot.com/2013/05/margahayuland-42-tahun-membangun.html
http://tech-kinodeon.blogspot.com/2013/02/agen-bola-ligabet88-promo-bonus-100.html
http://tech-kinodeon.blogspot.com/2013/04/penting-panas-perlu-dan-seruu.html
http://tech-kinodeon.blogspot.com/2013/05/korek-api-gas-fighter-indonesia.html


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources