SoFunction
Updated on 2025-03-01

Two examples of using ping command in C#

Method 1: Call cmd's ping command

 

private static string CmdPing(string strIp)
{

  Process p = new Process();  = "";//Set the program name   = false; //Close the use of Shell   = true;//Redirect standard input   = true;//Redirecting standard output   = true;//Redirect error output   = true;//Set not to display the window  string pingrst; (); ("ping " + strIp);
  ("exit");
  string strRst = ();
  
  if (("(0% loss)") != -1)
  {
    pingrst = "connect";
  }
  else if (("Destination host unreachable.") != -1)
  {
    pingrst = "Cannot reach the destination host";
  }
  else if (("Request timed out.") != -1)
  {
    pingrst = "time out";
  }
  else if (("Unknown host") != -1)
  {
    pingrst = "Cannot resolve host";
  }
  else
  {
    pingrst = strRst;
  }
  ();
  return pingrst;
}

Method 2: Use the ping class in C#

private void displayReply(PingReply reply) //Show results{

  Ping p1 = new Ping(); //Just just a demonstration, no error handling  
  PingReply reply = ("Fill in the IP address");
  
  StringBuilder sbuilder ;
  if ( == )
  {
    sbuilder = new StringBuilder();
    (("Address: {0} ",  ()));
    (("RoundTrip time: {0} ", ));
    (("Time to live: {0} ", ));
    (("Don't fragment: {0} ", ));
    (("Buffer size: {0} ", ));
    (());
  }
  else if ( == )
  {
    ("time out");
  }else{
    ("fail");
  }