14

I need my application to ping an address I'll specify later on and just simply copy the Average Ping Time to a .Text of a Label.

Any help?

EDIT:

I found the solution in case anyone is interested:

Ping pingClass = new Ping();        
PingReply pingReply = pingClass.Send("logon.chronic-domination.com");
label4.Text = (pingReply.RoundtripTime.ToString() + "ms");
Eric Schoonover
  • 47,184
  • 49
  • 157
  • 202
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254
  • 4
    Add your answer and a link to the relevant MSDN documentation as a proper answer instead of updating the question. You get reputation that way and it keeps the format of the QA consistent. Relevant MSDN link: http://msdn.microsoft.com/en-us/library/system.net.networkinformation.pingreply.aspx – Eric Schoonover Aug 15 '09 at 05:33

2 Answers2

34

Give a look the NetworkInformation.Ping class.

An example:

Usage:

PingTimeAverage("stackoverflow.com", 4);

Implementation:

public static double PingTimeAverage(string host, int echoNum)
{
    long totalTime = 0;
    int timeout = 120;
    Ping pingSender = new Ping ();

    for (int i = 0; i < echoNum; i++)
    { 
        PingReply reply = pingSender.Send (host, timeout);
        if (reply.Status == IPStatus.Success)
        {
            totalTime += reply.RoundtripTime;
        }
    }
    return totalTime / echoNum;
}
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • PingTimeAverage ("i.dont.exist.com", 1000) == 0 – Anton Tykhyy Aug 15 '09 at 05:56
  • 2
    @Anton, if the host cannot be resolved, the Ping.Send method will throw a PingException... http://is.gd/2hLjo – Christian C. Salvadó Aug 15 '09 at 06:33
  • @CMS I've tried replicating a small test for Ping(), and using "hostname.com" won't work for anything, stackoverflow.com/google.com or whatever. The only time Ping works, is with the actual IP. The [MSDN](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.send.aspx) for Ping says you can use hostname though... – JWiley Dec 12 '12 at 15:37
0

Just as a sidenote to this. There is allready a project on sourceforge doing about that what you want. This has also included an implementation of ICMP (RFC 792)

Sourceforge Project

Community
  • 1
  • 1
schoetbi
  • 12,009
  • 10
  • 54
  • 72